![](/img/trans.png)
[英]Access protected base class type for other base class template initialization
[英]Access attribute of template base class without “using”
我想在模板派生類B
的方法中使用模板基類A
中定義的屬性。
到目前為止,我發現using
作品。
但是,為A
每個單個屬性編寫一個using
語句很繁瑣。
如何避免編寫那么多的using
語句?
#include <iostream>
using namespace std;
template <typename T>
class A{
public:
A(){
a = 10;
}
//virtual destructor
virtual ~A(){
cout << "~A() is called" << endl;
}
protected:
T a;
} ;
template <typename T>
class B : public A<T>{
public:
void f(void){
cout << a << endl;
}
virtual ~B(){
cout << "~B() is called" << endl;
}
private:
using A<T>::a; //how to get rid of this?
} ;
int main(void){
B<int> bb;
bb.f();
}
因為要擴展一個類,它是依賴於模板參數, this
成為一個從屬名稱。 您必須使用this
明確:
template <typename T>
struct B : A<T>{
void f(){
std::cout << this->a << std::endl;
}
};
或者甚至可以指定類名稱:
template <typename T>
struct B : A<T>{
void f(){
std::cout << A<T>::a << std::endl;
}
};
第三種解決方案當然是using
語句。
// how to get rid of this?
你可以寫
void f(void){
cout << A<T>::a << endl;
}
要么
void f(void){
cout << this->a << endl;
}
擺脫using
語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.