Search code examples
c++c++11templatessfinaetemplate-specialization

How to accept only numbers and strings in templates in C++11?


As titlte says, in C++11, how can I declare a template that only accepts numbers (int, long, float and double) and strings?

template<typename T>
class CustomClass {
    public:
        T data;
};

Solution

  • Put this anywhere in the class definition:

    static_assert(std::is_arithmetic<T>::value ||
                  std::is_same<T, std::string>::value,
                  "Wrong argument type");
    

    Adjust condition to taste.