問題描述
當(dāng)一個(gè)模板從另一個(gè)模板公開繼承時(shí),是不是應(yīng)該可以訪問基本的公共方法?
When a template publicly inherits from another template, aren't the base public methods supposed to be accessible?
template <int a>
class Test {
public:
Test() {}
int MyMethod1() { return a; }
};
template <int b>
class Another : public Test<b>
{
public:
Another() {}
void MyMethod2() {
MyMethod1();
}
};
int main()
{
Another<5> a;
a.MyMethod1();
a.MyMethod2();
}
好吧,GCC 在這件事上胡說八道……我一定遺漏了一些非常明顯的東西(大腦融化).有幫助嗎?
Well, GCC craps out on this... I must be missing something totally obvious (brain melt). Help?
推薦答案
這是有關(guān)依賴名稱的規(guī)則的一部分.Method1
不是 Method2
范圍內(nèi)的依賴名稱.所以編譯器不會(huì)在依賴的基類中查找它.
This is part of the rules concerning dependent names. Method1
is not a dependent name in the scope of Method2
. So the compiler doesn't look it up in dependent base classes.
有兩種方法可以解決這個(gè)問題:使用 this
或指定基本類型.有關(guān)此非常近期的帖子的更多詳細(xì)信息或在 C++ 常見問題解答.另請(qǐng)注意,您錯(cuò)過了 public 關(guān)鍵字和分號(hào).這是您的代碼的固定版本.
There two ways to fix that: Using this
or specifying the base type. More details on this very recent post or at the C++ FAQ. Also notice that you missed the public keyword and a semi-colon. Here's a fixed version of your code.
template <int a>
class Test {
public:
Test() {}
int MyMethod1() { return a; }
};
template <int b>
class Another : public Test<b>
{
public:
Another() {}
void MyMethod2() {
Test<b>::MyMethod1();
}
};
int main()
{
Another<5> a;
a.MyMethod1();
a.MyMethod2();
}
這篇關(guān)于C++ 中的繼承和模板——為什么繼承的成員不可見?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!