[英]Member templates and inheritance
請考慮以下程序:
#include <iostream>
template <typename T>
struct A {
virtual void f(const T &) {
std::cout << "A::f(const T &)" << std::endl;
}
};
template <typename T>
struct B : A<T> {
template <typename U>
void f(const U &) override {
std::cout << "B::f(const U &)" << std::endl;
}
};
int main() {
B<int> *b = new B<int>;
A<int> *a = b;
a->f(42);
b->f(42);
}
編譯和執行:
g++ -std=c++11 test.cpp -o test &&
./test
輸出為:
A::f(const T &)
B::f(const U &)
輸出證明B::f
不會覆蓋A::f
,即使g++
接受了override
關鍵字(我認為這是一個錯誤)。
雖然, clang++
在此處不接受override
:
$ clang++ -std=c++11 test.cpp -o test && ./test
test.cpp:13:23: error: only virtual member functions can be marked 'override'
void f(const U &) override {
^~~~~~~~~
1 error generated.
如果我添加一個成員B::f
, 實際上覆蓋了A::f
,則輸出為:
B::f(const T &)
B::f(const T &)
但是如何從該重寫的實現中調用template <typename U> B::f(const & U)
:
#include <iostream>
template <typename T>
struct A {
virtual void f(const T &) {
std::cout << "A::f(const T &)" << std::endl;
}
};
template <typename T>
struct B : A<T> {
void f(const T &) override {
std::cout << "B::f(const T &)" << std::endl;
// how to call template <typename U> f(const U &) from here?
}
template <typename U>
void f(const U &) {
std::cout << "B::f(const U &)" << std::endl;
}
};
int main() {
B<int> *b = new B<int>;
A<int> *a = b;
a->f(42);
b->f(42);
}
謝謝
您可以像這樣顯式調用成員函數模板(或更確切地說:由它制成的成員函數):
void f(const T &x) override {
f<T>(x);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.