【问题标题】:template base class typedef members invisible模板基类 typedef 成员不可见
【发布时间】:2012-11-04 12:52:34
【问题描述】:

我知道编译器默认看不到“依赖名称”这一事实。但在回答其他 SO 问题(herehere 和最终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&lt;T&gt;::baseMember,2)使用前缀this-&gt;baseMember,3)添加a statement using TBase&lt;T&gt;::baseMember, 4) 使用启用许可模式的全局编译器开关。这些解决方案的优缺点和细节在stackoverflow.com/questions/50321788/…

标签: c++ templates typedef dependent-name


【解决方案1】:

你可能想这样做:

using MemberType = typename TBase<T>::MemberType; // new type alias syntax

typedef typename TBase<T>::MemberType MemberType; // old type alias syntax

using Base::member; 语法只能用于将非类型成员的声明带入作用域。


另请注意,实际上这些都不是必需的,您可以限定每次使用(对于具有基数的类型,对于具有this-&gt; 或基数的非类型),这将使符号依赖。

【讨论】:

  • 被这个问题困住了。遇到您的答案并在派生类中使用“this->”就像一个魅力。谢谢。
  • 实际上,您可以使用 using 语法,但需要 typename using typename TBase&lt;T&gt;::MemberType; 似乎对我有用
猜你喜欢
  • 2011-05-11
  • 1970-01-01
  • 2012-11-09
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多