gpt4 book ai didi

c++ - 基本模板继承成员,减少所需的输入

转载 作者:行者123 更新时间:2023-11-28 06:28:32 24 4
gpt4 key购买 nike

我有一个社区已知的问题(可以找到最完整的答案之一 here ),但我想知道是否有办法让编译器理解你想要访问 base无需使用模板成员 typedefthis如下:

#include <iostream>

template<typename T>
struct Base{
T a;
T a2;
};

template<typename T1, typename T2>
struct Derived : Base<T2>{
T2 b;

void member_fnc();
};

template<typename T1, typename T2>
void Derived<T1,T2>::member_fnc(){
typedef Base<T2> base;
std::cout << "a = " << base::a << std::endl; // or this->a;
std::cout << "a2 = " << base::a2 << std::endl; // or this->a2;
std::cout << "b = " << b << std::endl;
}

int main(){

Derived<int,double> der1;
der1.a = 1;
der1.a2 = 2;
der1.b = 1.1;
der1.member_fnc();

}

我觉得应该有一种方法可以让编译器告诉您要访问基本模板 Base<T2>无需键入或包含 using对于您要访问的每个成员,因为您可以使用 using 取消嵌套命名空间关键字,但到目前为止我找不到。有可能吗?

最佳答案

为什么不呢:

template<typename T1, typename T2>
struct Derived : Base<T2>{
typedef Base<T2> base;
using base::a;
using base::a2;

T2 b;
void member_fnc();
};

template<typename T1, typename T2>
void Derived<T1,T2>::member_fnc(){
std::cout << "a = " << a << std::endl; // or this->a;
std::cout << "a2 = " << a2 << std::endl; // or this->a2;
std::cout << "b = " << b << std::endl;
}

关于c++ - 基本模板继承成员,减少所需的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28091404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com