I'm trying to create a simple parser with metaparse to demonstrate how I can return my own custom types.
If I had a custom type ValNum
, how can I integrate this into a basic parser such that it is returned by the parser after matching a number? Apologies if this is trivial but I've been struggling to achieve this.
template<int Value>
struct ValNum {
constexpr static int value = Value;
};
CodePudding user response:
You can return custom types by using the transform
function along with a
metafunction.
Here's a really quick example of returning a custom type (butchering the identity
metafunction class they gave in the link and a couple over examples I found in their offical GitHub)
// custom type here
template<int Value>
struct ValNum {
constexpr static int value = Value;
};
struct identity
{
template <class T>
struct apply
{
// ValNum is my custom type
using type = ValNum<T::type::value>;
};
using type = identity;
};
typedef
grammar<_STR("int_token")>
::import<_STR("int_token"), token<transform<int_, identity>>>::type
expression;
typedef build_parser<entire_input<expression>> calculator_parser;
int main()
{
// hello is now our custom ValNum type
using hello = apply_wrap1<calculator_parser, _STR("13")>::type;
using std::cout;
using std::endl;
cout << hello::value << endl;
}
Hope this helps someone.