Static member initialization in a template class

不打扰是莪最后的温柔 提交于 2019-12-24 09:32:22

问题


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:


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.



来源:https://stackoverflow.com/questions/48268452/static-member-initialization-in-a-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!