5

我有这样的代码

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。

那么,如何判断 Template 类型是基本数据类型还是类呢?

4

4 回答 4

6

您可以使用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";
}
于 2013-04-21T14:24:50.590 回答
3

operator<<(std::ostream&)建议为任何类型重载T而不是使用printf():你怎么知道要使用什么格式说明符?

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

FWIW,std::is_class存在。

于 2013-04-21T14:25:11.380 回答
2

如果您没有 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 };
};

用于确定类型是否为类类型的简单模板。C++ 模板完整指南中的更多内容。

if (isClassT<T>::Yes) {
    std::cout << " Type is class " << std::endl;
}
于 2013-04-21T14:26:57.367 回答
2

我会使用打印辅助功能模板/重载:

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);在你的代码中说。

于 2013-04-21T14:30:53.473 回答