【问题标题】:What's wrong on inheritance template? [duplicate]继承模板有什么问题? [复制]
【发布时间】:2020-08-21 07:29:03
【问题描述】:

这是我的code

#include <iostream>

struct Plot {
    float test;
    
    Plot() : test(1.0f) {
    }
};

template <class T>
struct PlotTest : Plot {
    T *pModule;
    
    PlotTest(T *module) : Plot(), pModule(module) {

    }
};

template <class T>
struct PlotTestCustom : PlotTest<T> {
    PlotTestCustom(T *module) : PlotTest<T>(module) {
        test = 2.0f;
    }
};

int main()
{

}

但是当我编译时,PlotTestCustom 似乎看不到 float test; 变量(位于“主”父级上)。

我哪里错了?

【问题讨论】:

  • 我建议将标题更改为“为什么无法在模板中访问公共基类成员?”

标签: c++ templates inheritance


【解决方案1】:

在使用模板查找名称期间,它不会查看基类(例如,PlotTest 的特化可能不是从 Plot 继承的)。

因此你必须给编译器一个提示:

PlotTestCustom(T *module) : PlotTest<T>(module) {
    this->test = 2.0f;
}

这意味着通过将其设置为依赖名称来延迟查找直到实例化。

此处为完整示例:

#include <iostream>

struct Plot {
    float test;
    
    Plot() : test(1.0f) {
    }
};

template <class T>
struct PlotTest : Plot {
    T *pModule;
    
    PlotTest(T *module) : Plot(), pModule(module) {
        test = 3.0; // accessible Plot is not a dependent base class
    }
};

// specialization that does not inherit
template<>
struct PlotTest<int> {
};

template <class T>
struct PlotTestCustom : PlotTest<T> {
    PlotTestCustom(T *module) : PlotTest<T>(module) {
        this->test = 2.0f;
    }
};

int main()
{
    double d{};
    int i{};
    PlotTestCustom<double> p1{&d};
    //PlotTestCustom<int> p2{&i}; -> does not compile
}

【讨论】:

  • 但是在PlotTest 内我可以在没有this 的情况下访问它。为什么?
  • “例如,可能有一个不从 Plot 继承的 PlotTest 特化”嗯? PlotTest 将永远继承自 Plot: struct PlotTest : Plot
  • @markzzz 非依赖名称不在依赖基类中查找,但 Plot 不是依赖基类
  • @markzzz 看这个例子:godbolt.org/z/csvq9n
  • @markzzz 我顺便更新了我的答案
【解决方案2】:

test 在这里不是从属名称,因此您必须通过 this 指针访问它,从而推迟实际查找,直到知道模板参数为止

coliru

【讨论】:

    【解决方案3】:

    你必须给编译器一个提示,在你的对象的哪个部分可以找到这个成员:

    template <class T>
    struct PlotTestCustom : PlotTest<T> {
        PlotTestCustom(T *module) : PlotTest<T>(module) {
            Plot::test = 2.0f;
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多