模板化派生类时访问基本成员数据错误 [英] Accessing base member data error when derived class is templated

查看:58
本文介绍了模板化派生类时访问基本成员数据错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

奇怪的重复性模板存在以下问题,当我尝试访问CRTP基类的数据成员时遇到问题.

I have the following problem with the curiously recurring template, with a problem when I try to access the data member of CRTP base class.

template<typename T>
struct Base {
  int protectedData=10;
};

struct Derived : public Base<Derived> {
public:
  void method() {
    std::cout<<protectedData<<std::endl;
  };
};

int main ()
{
  Derived a;
  a.method();
}

上面的代码可以编译并正常运行,可以打印出"10",但是如果我将派生类进行模板化,例如:

The above code compiles and runs fine and I can get "10" printed, but if I have the derived class templated, like:

template<typename T>
struct Base {
  int protectedData=10;
};

template<typename T>
struct Derived : public Base<Derived<T> > {
public:
  void method() {
    std::cout<<protectedData<<std::endl;
  };
};

class A{};

int main ()
{
  Derived<A> a;
  a.method();
}

类A只是用作模板参数的虚拟类.但是编译器抱怨找不到"protectedData".错误信息如下:

class A is just a dummy class served as the template parameter. But the compiler complains cannot find the "protectedData". The error information is as following:

g++-4.9 test.cc -Wall -std=c++1y -Wconversion -Wextra
test.cc: In member function ‘void Derived<T>::method()’:
test.cc:26:11: error: ‘protectedData’ was not declared in this scope
    cout<<protectedData<<endl;

推荐答案

它实际上与CRTP无关,而事实上,对于访问依赖库的派生代码,您需要限定条件.

It doesn't really have to do with CRTP, but rather with the fact that for dependent-base-accessing derived code, you need to qualify things.

将行更改为

std::cout<<this->protectedData<<std::endl;

解决了.

请参见访问派生类中的基类成员

这篇关于模板化派生类时访问基本成员数据错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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