Concept for a function returning a templated entity

Viewed 107

I've been experimenting with adding concepts to a constexpr json parser and am struggling to define the proper Parser concept. My first attempt:

using parse_input_t = std::string_view;
template <typename T>
using parse_result_t = std::optional<std::pair<T, std::string_view>>;

// A parser for type `T` is a function: parse_input_t -> parse_result_t<T>
template <typename F, typename T>
concept Parser = std::is_invocable_r_v<parse_result_t<T>, F, parse_input_t>;

The problem with this is that I want to write functions with the signature:

template <Parser P>
auto func(P p);

That is, I don't want T in the interface.

I can accomplish what I want with something kind of ugly:

template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    requires requires(typename decltype(f(i))::value_type result)
    {      
        { f(i) } -> std::same_as<parse_result_t<decltype(result.first)>>;
    };
};

Is there a cleaner way to do this? I was hoping for something like:

template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    { f(i) } -> std::same_as<parse_result_t<auto>>;
};
2 Answers

Sure, you can do this.

Define a type trait to pull out the T from std::optional<std::pair<T, std::string_view>>:

template <typename T>
struct parser_type;
template <typename T>
struct parser_type<std::optional<std::pair<T, std::string_view>>> {
    using type = T;
};
template <typename T>
using parser_type_t = typename parser_type<T>::type;

Define a type trait around that that attempts to pull out the T from when you invoke F:

template <typename F>
using parser_result = parser_type_t<std::invoke_result_t<F, std::string_view>>;

and build a concept around that:

template <typename F>
concept Parser = requires {
    typename parser_result<F>;
};

You can then use parser_result<F> as the associated type of the parser. For example:

struct Ints {
    auto operator()(std::string_view) -> std::optional<std::pair<int, std::string_view>>;
};

static_assert(Parser<Ints>);
static_assert(std::same_as<int, parser_result<Ints>>);

Introduce a helper trait that verifies if a given type is parse_result_t, then use it in the concept on decltype(f(i)):

template <typename T>
constexpr bool is_parse_result_v = false;

template <typename T>
constexpr bool is_parse_result_v<parse_result_t<T>> = true;

template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    f(i);
    requires is_parse_result_v<decltype(f(i))>;
};

DEMO


Alternatively, use the helper trait in a separate concept definition, so as to avoid decltype:

template <typename T>
concept is_parse_result = is_parse_result_v<T>;

template <typename F>
concept Parser = requires(F f, parse_input_t i)
{
    { f(i) } -> is_parse_result;
};

DEMO 2

Related