如何解决继承模板有什么问题?
这是我的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;
变量(位于“主”父对象上)。
我在哪里错了?
解决方法
在使用模板进行名称查找期间,它不会查看基类(例如,可能存在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
}
,
test
在这里不是从属名称,因此您必须通过this
指针访问它,从而将实际查找推迟到知道模板参数为止
您必须给编译器一个提示,即可以在对象的哪一部分中找到该成员:
template <class T>
struct PlotTestCustom : PlotTest<T> {
PlotTestCustom(T *module) : PlotTest<T>(module) {
Plot::test = 2.0f;
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。