【发布时间】:2012-11-04 12:52:34
【问题描述】:
我知道编译器默认看不到“依赖名称”这一事实。但在回答其他 SO 问题(here、here 和最终on the C++ faq)时,有人告诉我using 声明可能会有所帮助。
所以我尝试了。
模板基类:
// regardless of the fact that members are exposed...
template<typename T>
struct TBase {
typedef T MemberType;
MemberType baseMember;
MemberType baseFunction() { return MemberType(); }
};
还有一个派生类,使用基类的成员:
template<typename T>
struct TDerived : public TBase<T> {
// http://www.parashift.com/c++-faq-lite/nondependent-name-lookup-members.html
// tells us to use a `using` declaration.
using typename TBase<T>::MemberType;
using TBase<T>::baseFunction;
using TBase<T>::baseMember;
void useBaseFunction() {
// this goes allright.
baseFunction();
++baseMember;
// but here, the compiler doesn't want to help...
MemberType t; //error: expected `;' before ‘t’
}
};
我试过this out on ideone。它有 gcc-4.3.3 和 gcc-4.5.1
这是预期的行为吗?我们应该如何解决访问父模板类成员类型定义的“依赖名称”法则?
【问题讨论】:
-
发生这种情况是因为两阶段名称查找(并非所有编译器都默认使用)。这个问题有4个解决方案:1)使用前缀
TBase<T>::baseMember,2)使用前缀this->baseMember,3)添加a statementusing TBase<T>::baseMember, 4) 使用启用许可模式的全局编译器开关。这些解决方案的优缺点和细节在stackoverflow.com/questions/50321788/…
标签: c++ templates typedef dependent-name