How do I write a class template that accepts only numeric types (int, double, float, etc.) as template?
I found the error messages received from the template approach highly cryptic (VS 2015), but found that a static_assert with the same type trait also works and lets me specify an error message:
#include
template
struct S
{
static_assert(std::is_arithmetic::value, "NumericType must be numeric");
};
template
NumericType add_one(NumericType n)
{
static_assert(std::is_arithmetic::value, "NumericType must be numeric");
return n + 1;
}
int main()
{
S i;
S s; //doesn't compile
add_one(1.f);
add_one("hi there"); //doesn't compile
}