如果我给出 10 意味着它应该打印它是一个整数 如果我给出 10.2 意味着它应该打印它是一个浮点 如果我给出 'a' 意味着它应该打印它是一个字符
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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.