Search code examples
c++templatesstdprimitive-typesenable-if

Struct, is fundamental template,C++


I want to check whether the template parameter of the struct is fundamental or not. So I created a struct

template<typename T, typename =  std::enable_if<std::is_fundamental_v<T>>>
struct Something {
};

And an empty struct

struct AStruct{
};

Using is_fundamental I expected that my struct will be "enabled" only and only if the template parameter T is one of the fundamental types like long long int , float and others...

But when I do specialization like

using Defined = Something<AStruct>;

It compiles fine, so what have I missed? or what have I done wrong?


Solution

  • It should be std::enable_if_t<std::is_fundamental_v<T>> (_t added) or typename std::enable_if<std::is_fundamental_v<T>>::type.

    I would suggest static_assert instead:

    • avoid the hijack with Something<AStruct, void> (can also be fixed with preferred std::enable_if_t<cond, int> = 0)
    • Your class would not be SFINAE friendly anyway, so that hard error allow custom message.
    • Simpler syntax :)