模板类中的静态成员初始化 [英] Static member initialization in a template class

查看:60
本文介绍了模板类中的静态成员初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在模板类内部初始化一个静态布尔,并且尝试像那样进行操作.我能看到的唯一区别是我对类型参数T有一个约束,但这会导致编译错误,为什么?我该如何解决?

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?

代码如下:

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;

错误是:

错误:用于声明的嵌套名称说明符' fraction< T> :: '未引用类,类模板或类模板的部分专业化
布尔分数< T> :: auto_reduce = true;

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;

推荐答案

也许更简单

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

撰写时

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

您说 fraction 是具有两个类型模板参数的类; std :: enable_if (如果该部分可用于为第二个参数分配默认值(并允许启用/不启用SFINAE工作),但是 fraction 是并且仍然是具有两个参数的模板 class ,您必须同时引用这两个参数,并且无需重复启用/不启用/默认部分来初始化第二个参数 auto_reduce .

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.

这篇关于模板类中的静态成员初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆