Brandon
Brandon

Reputation: 23485

How to use enable_if for restricting a whole class

I know I can use a static_assert and make sure that type T is numeric but I want to use std::enable_if. How can I force Vector3D class below to be numeric only using std::enable_if or std::conditional without inheriting?

template<typename T>
class Vector3D
{
    private:
        T X, Y, Z;
};

I tried:

template<typename T>
class Vector3D<typename std::enable_if<std::is_integral<T>::value, T>::type>
{
    private:
        T X, Y, Z;
};

Upvotes: 6

Views: 8309

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126502

If you really want to use enable_if, you can write your class template this way:

template<typename T, typename = typename     
    std::enable_if<std::is_arithmetic<T>::value>::type>
class Vector3D
{
    private:
        T X, Y, Z;
};

However, as others have noticed, you may be better off with using static_assert.

Upvotes: 9

Related Questions