我正在尝试实现一个模板类(在这里命名为Get<>
),给定一个结构H
,类型Get<H>::type
是H
本身,如果qualified-id H::der
不存在,否则是Get<H::der>::type
。我无法理解以下代码有什么问题:
#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?
}
我想要一些帮助,使这段代码按预期运行。更具体地说,我希望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;
};
模板Get<>
有一个默认的模板参数 - 这非常危险。根据V
是否相等int
,void
或double
,你会得到不同的结果。这是发生的事情:
Get<H2>::type
首先是Get<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;
};