引用基类模板的成员变量的简单方法
Simple way to reference member variables of base class templates
有没有办法在没有基类名称和范围解析运算符的情况下引用基类模板的成员变量?
template<typename D>
struct B0 {
int value;
};
struct D0: B0<D0> {
D0() {
B0<D0>::value = 1; // OK.
value = 1; // OK without `B0<D0>::`.
}
};
template<typename T>
struct B1 {
T value;
};
template<typename T>
struct D1: B1<T> {
D1() {
B1<T>::value = 1; // OK.
// value = 1; // Compile error without `B1<T>::`.
// Compile error: use of undeclared identifier 'value'
// `B1<T>::` is tedious everywhere `value` is referenced.
}
};
template<typename T, typename D>
struct B2 {
T value;
};
template<typename T>
struct D2: B2<T, D2<T>> { // CRTP
D2() {
B2<T, D2<T>>::value = 1; // OK.
// value = 1; // Compile error without `B2<T, D2<T>>::`.
// Compile error: use of undeclared identifier 'value'
// `B2<T, D2<T>>::` is more tedious for CRTP.
}
};
int main() {
return 0;
}
有没有可能不写B1<T>::
或B2<T, D2<T>>::
,这在引用value
任何地方都很乏味?
作为解决方案,您必须使名称value
依赖,以使其对名称查找可见。除了您展示的那个,您还可以:
-
用
using
介绍名称,template<typename T> struct D1: B1<T> { using B1<T>::value; // or move it in method's scope according to your intent D1() { value = 1; // OK. } };
-
以
this->
.template<typename T> struct D1: B1<T> { D1() { this->value = 1; // OK. } };
相关文章:
- 引用基类模板的成员变量的简单方法
- GDB 8.1 无法在单线程简单程序中跟踪 std::string 变量的值
- 简单的问题 - 如何从单独的"结构"内的'class'访问变量?
- 当使用Lua作为嵌入式语言(比如c++)时,有什么简单/方便的方法可以找到变量在Lua中的定义位置吗
- 我们可以在不使用head指针的情况下通过使用head的简单变量而不是head的指针来实现链表吗
- 简单加密算术库(SEAL)和SEAL::Ciphertext变量
- 创建一个简单的类及其变量和函数不断返回" segmentation fault (core dumped)"、C++
- 程序告诉我初始化在编写简单的C ++代码时不需要初始化的变量
- C++:我的简单计算器程序无法打印出来。我也认为我的变量命名不正确
- X 变量在最后一次尝试简单猜谜游戏时发生变化,C++
- 有没有更简单的方法可以做到:if(num1 > num2 && num1 > num3),以获得更大的变量列表进行比较?
- 简单,但找不到:使用类型类的 STL 队列的成员变量的语法
- 使用并集的简单结构中的成员变量别名
- 尝试在C 程序中设置简单的键盘输入.使用变量存储True或false
- C++,Visual Studio 2012和错误4700,用于简单程序中的类变量
- 简单变量列表参数C++
- 使用静态tmp变量为简单类型C++重新实现std::swap()
- 变量的值在使用C++的简单文本 RPG 游戏中不会更改
- 一个简单的猜谜游戏,继续使用除声明变量Y/N之外的任何其他字母
- 简单的引用变量赋值导致对象的全局指针出现segfault