模板基类typedef成员不可见 [英] template base class typedef members invisible

查看:63
本文介绍了模板基类typedef成员不可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道默认情况下依赖名称"对于编译器是不可见的.但是我被告知其他SO问题的答案(此处,最后在C ++常见问题解答上 ),使用 using 声明可能会有所帮助.

I'm aware of the fact that the 'dependent names' are not visible to the compiler by default. But I was told in answers to other SO questions (here, here, and ultimately on the C++ faq) that a using declaration may help.

所以我尝试了.

模板基类:

// regardless of the fact that members are exposed...
template<typename T>
struct TBase {
   typedef T MemberType;
   MemberType baseMember;
   MemberType baseFunction() { return MemberType(); }
};

以及使用基类成员的派生类:

And a derived class, using the base's members:

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’
   }
};

我在ideone上尝试了此问题.它具有gcc-4.3.3和gcc-4.5.1

I tried this out on ideone. It has gcc-4.3.3 and gcc-4.5.1

这是预期的行为吗?我们应该如何解决依赖名称"法来访问父模板类的成员typedef?

Is this expected behavior? How are we supposed to work around the 'dependent name' law for accessing parent template class' member typedefs?

推荐答案

您可能想做:

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

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

使用Base :: member; 的语法只能用于将非类型成员的声明纳入范围.

The syntax using Base::member; can only be used to bring the declarations of non-type members into scope.

还请注意,实际上这些都不是必需的,您可以限定每次使用(对于具有基数的类型,对于具有 this-> 或基数的非类型),这将使取决于符号.

Also note that none of these are actually required, you can qualify each use (for types with the base, for non-types with either this-> or the base) and that will make the symbol dependent.

这篇关于模板基类typedef成员不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆