Reputation: 21
If I give 10 means it should print it is a integer If I give 10.2 means it should print it is a float If I give 'a' means it should print it is a char
Upvotes: 2
Views: 94
Reputation: 1313
You can use type_traits and template specialization to achieve this. Please see this example for more info:-
#include <iostream>
#include <type_traits>
template<typename T>
struct is_integer{
static const bool value = false;
};
template<>
struct is_integer<int>{
static const bool value = true;
};
template<typename T>
struct is_char{
static const bool value = false;
};
template<>
struct is_char<char>{
static const bool value = true;
};
template<typename T>
void printType(T t){
if(is_integer<T>::value)
{
std::cout<<"Value is integer"<<std::endl;
}
else if(is_char<T>::value)
{
std::cout<<"Value is char"<<std::endl;
}
else if(std::is_floating_point<T>::value)
{
std::cout<<"Value is float"<<std::endl;
}
}
int main()
{
int i = 10;
char j = 'a';
float k = 10.2f;
printType(i);
printType(j);
printType(k);
return 0;
}
Upvotes: 0
Reputation: 598319
Read the input as a std::string
first.
Then, pass the string to std::stoi()
, and if it consumes the whole string without error, print the resulting integer.
Otherwise, pass the string to std::stof()
, and if it consumes the whole string without error, print the resulting float.
Otherwise, print the string as-is.
Upvotes: 1