如何确定模板类型是基本类型还是类

How to determine whether the template type is a basic type or a class

本文关键字:类型 何确定      更新时间:2023-10-16

我有这样的代码

template <typename T> void fun (T value)
{
    .....
    value.print ();  //Here if T is a class I want to call print (), 
                     //otherwise use printf
    .....
}

现在,要打印值,如果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";
}

建议对任何类型的T重载operator<<(std::ostream&),而不是使用printf():您如何知道使用哪种格式说明符?

template <typename T> void fun (T value)
{
    .....
    std::cout << value <<  std::endl;
    .....
}

std::is_class存在

如果您没有c++ 11的支持,可以选择。

template<typename T>
class isClassT {
private:
    typedef char One;
    typedef struct { char a[2]; } Two;
    template<typename C> static One test(int C::*);
    template<typename C> static Two test(…);
public:
    enum { Yes = sizeof(isClassT<T>::test<T>(0)) == 1 };
    enum { No = !Yes };
};
一个简单的模板,用来判断type是否为类类型。c++模板完整指南中的更多内容。
if (isClassT<T>::Yes) {
    std::cout << " Type is class " << std::endl;
}

我会使用打印辅助函数模板/overload:

template <typename T>
void print(T const & t) { t.print(); }
template <typename U>
void print(U * p) { std::printf("%p", static_cast<void*>(p)); }
// we really an enable_if on is_object<U>::value here...
void print(char x) { std::printf("%c", x); }
void print(int x) { std::printf("%d", x); }
// etc. for all fundamental types

那么您可以简单地在代码中使用print(value);