模板中的静态成员初始化 class

Static member initialization in a template class

我需要在模板 class 中初始化一个静态布尔值,我试着像 this 那样做。我能看到的唯一区别是我对类型参数 T 有约束,但这会导致编译错误,为什么?我该如何解决?

代码如下:

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;

错误是:

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 是一个有两个类型模板参数的 class; std::enable_if if 部分可用于为第二个参数分配默认值(并允许 enable/not 启用 SFINAE 工作)但 fraction 是并且仍然是模板 class两个参数,你必须引用两个参数并且不需要重复 enable/not enable/default 部分来初始化第二个参数 auto_reduce.