如何初始化具有类型特征的 class 模板的静态数据成员?
How can I initialize a static data member of a class template with type traits?
我试过使用类似的东西,但初始化似乎不起作用。当我删除类型特征时,它会按预期工作。
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
的名称是为内部实现保留的。
我试过使用类似的东西,但初始化似乎不起作用。当我删除类型特征时,它会按预期工作。
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
的名称是为内部实现保留的。