Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
};
like image 202
GianMS Avatar asked Nov 25 '25 12:11

GianMS


1 Answers

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.

like image 107
Igor Tandetnik Avatar answered Nov 28 '25 03:11

Igor Tandetnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!