1

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?

satanik
  • 572
  • 7
  • 21
  • 1
    Totally unrelated to your problem, but identifiers with leading underscore followed by a capital letter are reserved for the compiler/library implementation. [[Reference](http://stackoverflow.com/a/228797/440558)] – Some programmer dude Apr 05 '15 at 13:31

1 Answers1

1

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.

Mateusz Grzejek
  • 11,698
  • 3
  • 32
  • 49
  • Is it then a better way to use a static_assert inside the class to say one should only use the template with integral types? – satanik Apr 05 '15 at 13:34
  • 1
    No, `static_assert` is preferred if you want to check if some required property of a particular type is met. For example: you may want user to supply integer type, that is at least 32 bit wide - `std::enable_if` can be used to check if `T` is integral **at all** and then `static_assert` can be used to check whether `sizeof(T) >= 4`. Note, that even `std` library implementation uses `enable_if` extensively for things like "is integer". – Mateusz Grzejek Apr 05 '15 at 13:37
  • 1
    @satanik Jjust place a `static_assert` inside the class. E.g. `class Foo { static_assert(std::is_integral::value, "..."); ... };` – Some programmer dude Apr 05 '15 at 13:37