Dne pondělí 2. května 2016 9:09:05 UTC+2 Juha Nieminen napsal(a):
> Non-type template parameters can be used for example like this:
>
> template<int N> class Test { ... };
>
> However, this fixes that non-type parameter to be of type int. Is it in
> any way possible to make the instantiating code decide what that type
> actually is? In other words, rather than the template itself, it's
> the insantiating code that decides whether it's an int, and unsigned,
> or something else. In other words, these would be different:
>
> Test<5> test1;
> Test<5U> test2;
> Test<5LL> test3;
>
I do not know any nice way. You can do this:
template<typename T, T VALUE>
struct X
{
static const T Value = VALUE;
};
To make it easier, you can define wrapping macro:
#define MAKE_X(val) X<std::decay<decltype(val)>::type, (val)>
MAKE_X(20) x1;
MAKE_X('a') x2;
MAKE_X(L'a') x3;
MAKE_X(0ULL) x4;
std::cout << sizeof(x1.Value) << '\n';
std::cout << sizeof(x2.Value) << '\n';
std::cout << sizeof(x3.Value) << '\n';
std::cout << sizeof(x4.Value) << '\n';
For integral types it should work in C++11.