我尝试使用类似的东西,但初始化似乎不起作用。当我删除类型特征时,它会按预期工作。
template<typename _T, typename = std::enable_if_t<std::is_integral<_T>::value>>
struct Foo
{
static int bar;
};
template<typename _T>
int Foo<_T>::bar = 0;
如何正确初始化这样一个静态变量?
最佳答案
那是因为你没有正确使用 std::enable_if
。
template<typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
struct Foo;
template <typename T>
struct Foo<T, false> //Partial specialization
{
// if T is not integral, Foo becomes empty class
};
template <typename T>
struct Foo<T, true> //Partial specialization
{
static int bar;
};
然后:
template<typename T>
int Foo<T, true>::bar = 0;
我把_T
改成了T
,因为名字定义为_X
, __X
or __x
保留用于内部实现。
关于c++ - 如何初始化具有类型特征的类模板的静态数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29457776/