如何初始化具有类型特征的类模板的静态数据成员

How can I initialize a static data member of a class template with type traits?

本文关键字:静态 数据成员 特征 初始化 类型      更新时间:2023-10-16

我试着使用这样的东西,但初始化似乎不起作用。当我删除类型特征时,它就会按预期工作。

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__x的名称是为内部实现保留的。