基本模板继承成员,减少所需的输入
Base template inheritance members, reduce typing needed
我有一个社区已知的问题(可以找到最完整的答案之一 here),但我想知道是否有办法让编译器理解你想要访问基本模板成员而不需要使用 typedef
或 this
,如下所示:
#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;
}
我有一个社区已知的问题(可以找到最完整的答案之一 here),但我想知道是否有办法让编译器理解你想要访问基本模板成员而不需要使用 typedef
或 this
,如下所示:
#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;
}