成员模板和继承
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.
如果我添加一个真正覆盖A::f
的成员B::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);
}
相关文章:
- 为什么我可以通过SubBase类的公共继承方法打印出基类的私人继承成员
- 派生类调用使用非继承成员的继承函数
- 如果存在具有不同参数的继承成员,为什么对 C++ 结构函数的调用不明确?
- C :原始成员与继承成员的优先级
- 更改继承成员的地址
- C 是否可以不继承成员
- 使用模板的继承阴影继承成员
- 继承成员功能的模板专业化
- 不允许继承成员,为什么
- 派生模板类和继承成员变量的语法谜题
- 继承成员地址的C++标准
- 多级继承成员访问
- 访问专用模板的私有/继承成员变量
- 基模板继承成员,减少所需的类型
- 继承成员函数指针
- 模板专用化类不继承成员
- C++14正在初始化类构造函数初始化列表中的继承成员
- 具有专门初始化的继承成员变量
- 模板继承成员字段
- 访问数据成员的继承成员函数