c++ - 如何判断模板类型是基本类型还是类

标签 c++ templates types

我有这样的代码

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/

相关文章:

c++ - 为什么 C++ 的 64 位整数扩展名为 "long long"?

c++ - return后可以写语句吗?

c++ - while循环比较中getline的实现

c++ - 类方法的显式特化 - 符号已定义

python - 找到较低级别的模板

c# - 输入来自 InvalidCastException 的数据

f# - 列表中项目的比较

c++ - 混合模式程序集(C++/CLI 项目)能否在 .NET Core 上运行?

c++ - 为什么 GCC 错误地检测到移位计数溢出?

C++ 获取函数参数的字节数