当模板类继承自另一个模板类时,必须再次重新定义基类中的typedef(即它们不会自动继承),并且需要限定基类中的函数调用.这是为什么?这不是明确的吗?
因此,如果我有20个模板类,都定义了相同的typedef,我无法引入包含这些定义的基类并从中继承,因为我必须在每个类中重新定义typedef,这会破坏目的.这使源代码变得如此不必要地冗长.
我可以看到这已经在question中讨论过了,但我不明白这个评论
The C++ name lookup rules specify that a name is only searched in a templated base classes if it depends on a template parameter (if it is a “dependent name”). If a name does not depend on a template parameter it isn’t searched there.
这是什么原因?对我来说完全是无稽之谈.
也许,下面的代码片段会更好地说明我的问题:
#include <iostream>
template <unsigned N,typename T>
struct A
{
typedef T U;
static void foo(T x) { std::cout << N + x << "\n"; }
};
template <unsigned N,typename T>
struct B : public A<N,T>
{
// Why do I have to redeclare U? Isn't is unambiguous already?
typedef typename A<N,T>::U U;
// why do I have to specify B::? Isn't it unambiguous already?
static void zoo(U x) { B::foo(x); }
};
int main()
{
B<2,int>().zoo(3);
B<2,double>().zoo(3.5);
return 0;
}
解决方法
基本原因是课程可以专业化:
template<class T>
struct A {};
template<class T>
struct B : A<T> {
typedef typename A<T>::referent target;
void niceName() {A<T>::uglyName();}
};
template<class T>
struct A<T*> {
typedef T referent;
void uglyName();
};
B<int*>::target i; // OK: int
当然,相反的情况(主要模板定义有用的东西,我们只是担心专业化可能会改变或删除它们)更常见,这使得规则似乎是任意的.