Skip to content

Basic helpers

Raymond Chen edited this page Mar 20, 2019 · 2 revisions

The impl/base.h header file provides some basic helper functions. All of the helper functions are in the xlang namespace.

throw_invalid

void throw_invalid(std::string const& message);
void throw_invalid(std::string message, T const&...);

The xlang::throw_invalid function throws a std::invalid_argument exception with the specified message. If multiple parameters are passed, they are concatenated into a single string.

c_str

template<typename T>
const T* c_str(std::basic_string_view<T> const& view) noexcept;

The xlang::c_str function verifies that the std::basic_string_view is followed by a null terminator and returns a pointer to the start of the view.

If the view is not followed by a null terminator, the process is terminated with std::terminate.

starts_with

bool starts_with(std::string_view const& value, std::string_view const& match) noexcept;

The xlang::starts_with function returns true if value starts with match. The comparison is case-sensitive.

struct visit_overload

template <typename...T> struct visit_overload : T... { using T::operator()...; };

The xlang::visit_overload template struct is a helper type for xlang::call. It aggregates all of the template types and inherits all of their operator() methods.

call

template<typename V, typename... C>
void call(V&& variant, C&&...call);

The xlang::call function visits a variant by calling the handler that matches the type currently in the variant. The handlers must be movable. (Typically they are lambdas.)

Example:

std::variant<int, double, void*> v;
call(v, [](int i) { handle_integer(i); },
        [](double d) { handle_double(d); },
        [](auto&&) { /* ignore */ });

The handlers must collectively encompass all of the possible types of the variant. In our case, we used a generic lambda to "soak up" all the unhandled types and ignore them.

Throws std::bad_variant_access if the variant is valueless_by_exception.

Known limitations:

  • The callable must be class or structure type, such as a lambda or std::function. It cannot be a function pointer.
Clone this wiki locally