Specialize static constexpr data element

I have a class to describe some type attributes.

template<typename T> struct my_traits { static constexpr int some_trait = 0; static constexpr T min() { return std::numeric_limtis<T>::min(); } static constexpr T max() { return std::numeric_limits<T>::max(); } }; 

I want to specialize my_traits::some_trait , but when I try:

 template<> constexpr int my_traits<int>::some_trait = 1; 

The compiler complains that my_traits::some_trait already has an initializer. Of course, I can specialize in this:

 template<> struct my_traits<int> { static constexpr int some_trait = 1; // min and max }; 

but then I have to redefine all the other functions, although they will be exactly the same.

So, how can I specialize my_traits<int>::some_trait without repeating min and max ?

+8
c ++ c ++ 14 template-specialization
source share
1 answer

There are several ways to do this. @Piotr Skotnicki and @Niall mentioned initialization through some helper, which may be specialized. In general, just rebuild your code so that you can specialize some classes or functions, and then use (in composition or inheritance) specialized parts in parts that you do not need to specialize.

As an example of an alternative to comments, this is a specialized base:

 #include <iostream> #include <limits> template<typename T> struct my_specializing_traits { static constexpr int some_trait = 0; }; template<> struct my_specializing_traits<int> { static constexpr int some_trait = 1; }; 

Now you can just subclass it into the general part:

 template<typename T> struct my_traits : public my_specializing_traits<T> { static constexpr T min() { return std::numeric_limits<T>::min(); } static constexpr T max() { return std::numeric_limits<T>::max(); } }; 

The following shows how it is used (it outputs 0 and 1)

 int main() { std::cout << my_traits<char>().some_trait << std::endl; std::cout << my_traits<int>().some_trait << std::endl; } 
+5
source share

All Articles