2012-11-24 32 views
5

我想实现一个模板类(名为Get <>在这里),给定结构H,类型Get<H>::typeH本身如果qualified-idH::der不存在,并且是Get<H::der>::type否则。我不明白下面的代码有什么问题:C++递归型性状

#include <iostream> 
#include <typeinfo> 
using namespace std; 

template<class U, class V = void> 
struct Get 
{ 
    static const char id = 'A'; 
    typedef U type; 
}; 

template<class U> 
struct Get<U,typename U::der> 
{ 
    static const char id = 'B'; 
    typedef typename Get<typename U::der>::type type; 
}; 

struct H1 
{ }; 
struct H2 
{ typedef double der; }; 
struct H3 
{ typedef void der; }; 
struct H4 
{ typedef H2 der; }; 

void print(char id, const char* name) 
{ 
    cout << id << ", " << name << endl; 
} 
int main(int , char *[]) 
{ 
    print(Get<H1>::id, typeid(Get<H1>::type).name()); // prints "A, 2H1", OK 
    print(Get<H2>::id, typeid(Get<H2>::type).name()); // prints "A, 2H2", why? 
    print(Get<H3>::id, typeid(Get<H3>::type).name()); // prints "B, v" , OK 
    print(Get<H4>::id, typeid(Get<H4>::type).name()); // prints "A, 2H4", why? 
} 

我想要一些帮助,以使此代码的行为如预期。更具体地说,我希望获取< H2> ::类型等于,和相同得到< H4> ::类型

+0

可能重复http://stackoverflow.com/questions/3008571/template-specialization-to-use -default-type-if-class-member-typedef-does-not-exi) –

+2

litb的'tovoid'技巧在这个答案中解决了你的问题:http://stackoverflow.com/a/3009891/245265 –

+0

不错的把戏,天堂我不知道。 – ipc

回答

2

当我给一个+1到@ipc的答案,这是很好的C++ 11启用编译器,用于C++编译器03你应使用不同的方法,因为函数的模板参数的默认值在C++ 03中不受支持。所以我有这样的代码:

​​ [模板专门使用默认的类型,如果类成员的typedef不存在(的
+0

如果你正在使用'boost :: enable_if'('std :: enable_if'是C++ 11),'typename boost :: enable_if :: type'应该也可以工作并且使得'is_type '助手类多余。 – ipc

+0

@ipc其实我在我的真实项目中使用'boost :: enable_if',但它不是这样,因为'boost :: enable_if'的条件应该是'mpl'布尔常量。正确的代码是'boost :: enable_if >'。请记住'std :: enable_if'属于'TR1'而不是C++ 11。 – BigBoss

+0

好吧,你是对的。但是'std :: enable_if'仍然是C++ 11,因为在'std'中嵌入'std :: tr1'是非标准的。 – ipc

2

模板Get<>有一个默认的模板参数 - 这是非常危险的。取决于V是否等于intvoiddouble您会得到不同的结果。这是发生了什么事情:

Get<H2>::typeGet<H2, void>第一名(与id='A')。现在来检查,是否有专业化。你的B是Get<U,typename U::der>,它变成Get<U, double>。但这与Get<H2, void>不匹配,因此选择A。事情变得有趣与Get<H2>::type。然后变体B也是Get<U, void>并提供更好的匹配。但是,该方法不适用于所有类型。

这是我会如何实现Get

template<class U> 
class Get 
{ 
    template <typename T, typename = typename T::der> 
    static typename Get<typename T::der>::type test(int); 
    template <typename T> 
    static T test(...); 
public: 
    typedef decltype(test<U>(0)) type; 
};