From the C++11
you can use the function std::is_arithmetic
of the standard library type_traits
to check whether an arbitrary type is an integer or a real number (floating point), see only:
#include <iostream>
#include <type_traits>
class A {};
int main()
{
std::cout << std::boolalpha;
std::cout << "A: " << std::is_arithmetic<A>::value << '\n';
std::cout << "bool: " << std::is_arithmetic<bool>::value << '\n';
std::cout << "int: " << std::is_arithmetic<int>::value << '\n';
std::cout << "int const: " << std::is_arithmetic<int const>::value << '\n';
std::cout << "int &: " << std::is_arithmetic<int&>::value << '\n';
std::cout << "int *: " << std::is_arithmetic<int*>::value << '\n';
std::cout << "float: " << std::is_arithmetic<float>::value << '\n';
std::cout << "float const: " << std::is_arithmetic<float const>::value << '\n';
std::cout << "float &: " << std::is_arithmetic<float&>::value << '\n';
std::cout << "float *: " << std::is_arithmetic<float*>::value << '\n';
std::cout << "char: " << std::is_arithmetic<char>::value << '\n';
std::cout << "char const: " << std::is_arithmetic<char const>::value << '\n';
std::cout << "char &: " << std::is_arithmetic<char&>::value << '\n';
std::cout << "char *: " << std::is_arithmetic<char*>::value << '\n';
}
Exit:
A: false
bool: true
int: true
int const: true
int &: false
int *: false
float: true
float const: true
float &: false
float *: false
char: true
char const: true
char &: false
char *: false
In your case:
#include <type_traits>
template<class T>
T soma(const T& x, const T& y) {
static_assert( std::is_arithmetic<T>::value, "Tipo de argumento inválido, O argumento precisa ser numérico");
return x + y;
}
I think you’ve got it all https://rosettacode.org/wiki/Determine_if_a_string_is_numeric
– user60252