Has*_*ken 4 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
.....
}
Run Code Online (Sandbox Code Playgroud)
现在,要打印该值,如果T是一个类,我想调用该对象的print函数,但如果T是基本数据类型,我只想使用printf.
那么,我如何找到模板类型是基本数据类型还是类?
你可以使用std::is_class(也可能std::is_union).细节取决于您对"基本类型"的定义.查看更多关于类型的支持这里.
但请注意,在C++中,通常会重载std::ostream& operator<<(std::ostream&, T)打印用户定义的类型T.这样,您无需担心传递给函数模板的类型是否为类:
template <typename T> void fun (T value)
{
std::cout << value << "\n";
}
Run Code Online (Sandbox Code Playgroud)