NUR Template-Spezialisierungen zulassen?
-
Hallo,
ist es möglich, bei einer Templateklasse NUR templatespezialisierungen zuzulassen? Beispiel:template<unsigned int N> class zahl { //... };Der Parameter N darf aber nur eine Potenz von zwei sein. D.h, es soll nur Klassen geben, deren N = 2^x ist. Außerdem möchte ich nicht 32 verschiedene Spezialisierungen per Hand schreiben.
template<> class zahl< N == 2^x > { //... };Weis jemand, wie/ob so etwas möglich ist?
-
Geht, ist aber etwas umständlich. Beispielsweise so:
struct empty { }; template<bool> struct assert_type { }; template< > struct assert_type<true> { typedef empty type; }; template<unsigned x> struct bitcounter { static unsigned const val = (x & 1) + bitcounter<(x >> 1)>::val; }; template<> struct bitcounter<0> { static unsigned const val = 0; }; template<unsigned x> struct is_pow2 { typedef typename assert_type<bitcounter<x>::val == 1>::type type; }; template<unsigned x> struct can_only_use_pow2 : private is_pow2<x>::type { };Wenn can_only_use_pow2 mit etwas anderem als einer Potenz von 2 konkretisiert wird, hat assert_type<bitcounter<x>::val == 1> keinen Member type, und die private Ableitung schlägt fehl.
-
Etwas einfacher:
template <unsigned int N> struct is_power_of_two { static const bool value = (N%2 == 0) && is_power_of_two<N/2>::value; }; template <> struct is_power_of_two<1> { static const bool value = true; }; template <> struct is_power_of_two<0> { static const bool value = false; };
-
Darum liebe ich C++ :xmas1:
-
template <unsigned int N> struct is_power_of_two { static const bool value = N != 0 && ( N & N - 1 ) == 0; };
-
camper schrieb:
template <unsigned int N> struct is_power_of_two { static const bool value = N != 0 && ( N & N - 1 ) == 0; };Eher darum.

Nicht schlecht, camper!