I tried to use something like this but the initialization seems not to work. When I remove the type trait, then it works as expected.
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;
How to properly initialize such a static variable?
That's because you used std::enable_if
not quite properly.
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;
};
And then:
template<typename T>
int Foo<T, true>::bar = 0;
I changed _T
to T
, because name defined as _X
, __X
or __x
are reserved for internal implementation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.