mon*_*olo 5 c++ templates type-traits
我正在尝试实现一个模板类(此处名为Get <>),给定结构H,如果不存在,则类型Get<>为H自身Get<H>::type H,H::der否则为.我无法理解以下代码有什么问题:
#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?
}
Run Code Online (Sandbox Code Playgroud)
我想要一些帮助,使这段代码按预期运行.更具体地说,我希望Get <H2> :: type等于double,而Get <H4> :: type则相同.
虽然我给@ipc答案+1,并且它对于启用C ++ 11的编译器非常好,但对于C ++ 03编译器,您应该使用不同的方法,因为C中不支持函数模板参数的默认值++03。所以我有这个代码:
template<class U, class V = void>
struct Get
{
static const char id = 'A';
typedef U type;
};
template< class T >
struct is_type {
static const bool value = true;
};
template<class U>
struct Get<U,
typename std::tr1::enable_if<is_type<typename U::der>::value, void>::type>
{
static const char id = 'B';
typedef typename Get<typename U::der>::type type;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
399 次 |
| 最近记录: |