Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a template template parameter take a numeric value?

Tags:

c++

templates

I want to have a template parameter accept a template that has a numeric template argument.

This example maybe overly simplified, but I'd like something like this:

template <int X>
struct XX
{
  static const int x = X;
};

template<typename TT, TT V, template<V> TX>
void fnx(TX<V> x)
{
  static_assert(V == TX::x, "IMPOSSIBLE!");
}

void fny()
{
  fnx(XX<1>())
}

I must not be understanding the syntax for this, as it must be possible. How would I accomplish this?

like image 648
Adrian Avatar asked May 22 '16 15:05

Adrian


Video Answer


1 Answers

Just fixing up your syntax a bit - since the template template parameter is improperly specified, we'd end up with something like this:

template <typename T, template <T > class Z, T Value>
//                    ^^^^^^^^^^^^^^^^^^^^^
void foo(Z<Value> x) { }

However, the compiler can't deduce T here - it's a non-deduced context. You'd have to explicitly provide it:

foo<int>(XX<1>{});

That's pretty annoying. I cannot even write a type trait such that non_type_t<XX<1>> is int (where that type trait does actual introspection on the type, not something that trivially returns int).


There is a proposal to improve this process (P0127) by amending the non-deduced context-ness of non-type template arguments.

like image 66
Barry Avatar answered Sep 17 '22 15:09

Barry