Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Not fixing the type of a non-type template parameter

23 views
Skip to first unread message

Juha Nieminen

unread,
May 2, 2016, 3:09:05 AM5/2/16
to
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;

--- news://freenews.netfront.net/ - complaints: ne...@netfront.net ---

Ondra Holub

unread,
May 2, 2016, 4:02:35 AM5/2/16
to
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.

Ondra Holub

unread,
May 2, 2016, 4:07:11 AM5/2/16
to
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;
>

Of course, std::decay is not needed, just

#define MAKE_X(val) X<decltype(val), (val)>

should be enough :-)
0 new messages