我想实现一个模板类(名为Get <>在这里),给定结构H,类型Get<H>::type
是H
本身如果qualified-id
H::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> ::类型。
可能重复http://stackoverflow.com/questions/3008571/template-specialization-to-use -default-type-if-class-member-typedef-does-not-exi) –
litb的'tovoid'技巧在这个答案中解决了你的问题:http://stackoverflow.com/a/3009891/245265 –
不错的把戏,天堂我不知道。 – ipc