2013-04-21 77 views
3

我的代码是这样的如何确定的模板类型是基本型或类

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。

那么,如何找到模板类型是基本数据类型还是类?

+3

你打算使用哪种格式的字符串作为基本类型? – Xeo 2013-04-21 14:24:58

回答

5

您可以使用std::is_class(也可能是std::is_union)。细节取决于您对“基本类型”的定义。有关支持类型的更多信息,请参阅here

但请注意,在C++中,打印用户定义类型T时通常会重载std::ostream& operator<<(std::ostream&, T)。这样,你不需要担心传递给你的函数模板类型是否是类或不:

template <typename T> void fun (T value) 
{ 
    std::cout << value << "\n"; 
} 
+2

+1我几乎可以在这里“我怎么用这个”火车来了。同上hmjd的答案。 (和两者都+1)。 – WhozCraig 2013-04-21 14:27:25

+0

@WhozCraig正确,答案就是“你不要,你输出流操作符超载......” – juanchopanza 2013-04-21 14:33:29

+0

同意。 (填料)。 – WhozCraig 2013-04-21 14:37:29

3

推荐超载operator<<(std::ostream&)任何类型T,而不是使用printf():你怎么会知道是什么格式说明使用?

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

FWIW,std::is_class存在。

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 }; 
}; 

一个简单的模板,用于确定type是否是类的类型。更多C++ Templates a Complete Guide

if (isClassT<T>::Yes) { 
    std::cout << " Type is class " << std::endl; 
} 
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);