我有一个类型 Type
和一个变量 tmp
:
template<typename Type> myFunction()
{
/* SOMETHING */ tmp = 0;
};
如果 Type
是浮点类型,我想将 tmp
声明为 Type
并且声明为 double
如果 Type
是整型。如何在 C++11 中做到这一点?
最佳答案
typedef typename std::conditional<
std::is_floating_point<T>::value,
T, //if floating, ::type = T
double //else, ::type = double
>::type value_type;
value_type tmp; //declare variable
我假设 T
只能是算术类型。如果需要,可以使用 std::is_arithmetic
先检查一下。在此处查看其他有用的类型特征:
关于C++11 type_traits : same type if floating point, double 如果是整型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12044364/