我有这样的代码
template <typename T> void fun (T value)
{
.....
value.print (); //Here if T is a class I want to call print (),
//otherwise use printf
.....
}
现在,要打印值,如果 T 是类,我想调用对象的打印函数,但如果 T 是基本数据类型,我只想使用 printf。
那么,如何判断模板类型是基本数据类型还是类呢?
最佳答案
你可以使用 std::is_class
(可能还有 std::is_union
)。详细信息取决于您对“基本类型”的定义。查看更多类型支持 here .
但请注意,在 C++ 中,通常会重载 std::ostream& operator<<(std::ostream&, T)
用于打印用户定义的类型 T
.这样,您就不必担心传递给函数模板的类型是否是类:
template <typename T> void fun (T value)
{
std::cout << value << "\n";
}
关于c++ - 如何判断模板类型是基本类型还是类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16132123/