2

I need to initialize a static bool inside of a template class and I tried to do it like this. The only difference I can see is that I have a constraint on type parameter T but this causes a compilation error, why? How can I solve this?

Code is the following:

template<class T, class = typename enable_if<is_any_integral<T>::value>::type>
class fraction {
    static bool auto_reduce;

    // ...
};

template<class T, class = typename enable_if<is_any_integral<T>::value>::type>
bool fraction<T>::auto_reduce = true;

And the error is:

error: nested name specifier 'fraction<T>::' for declaration does not refer into a class, class template or class template partial specialization
bool fraction<T>::auto_reduce = true;

1 Answer 1

2

Maybe simpler

template<class T, class V>
bool fraction<T, V>::auto_reduce = true;

When you write

template<class T, class = typename enable_if<is_any_integral<T>::value>::type>
class fraction

you say that fraction is a class with two type template paramenters; the std::enable_if if part is useful to assign a default value to the second parameter (and to permit the enable/not enable SFINAE works) but fraction is and remain a template class with two parameters, you have to cite both and there is no need to repeat the enable/not enable/default part for second parameter initializing auto_reduce.

3
  • But do you have to necessarily introduce V? Will template<class T, typename = void> do? Jan 15, 2018 at 18:19
  • 2
    @水飲み鳥 - take in count that V (as T) is just the name of a template parameter; you can also change names, if you want, and initialize auto_reduce as template<class A, class B> bool fraction<A, B>::auto_reduce = true;; I've named the second as V because the default value is void but is absolutely arbitrary. In class declaration you can avoid to use the name of the second parameters because isn't used (is just a SFINAE trick to enable/not enable); but externally initializing a static variable you have to reference it so you have to give it an (arbitrary) name.
    – max66
    Jan 15, 2018 at 18:25
  • @max66 Thanks for the comment. It seems that initializing the static requires the full type qualification of the class template fraction: in this case, two type parameters (as you said). Jan 15, 2018 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.