成员模板和继承

Member templates and inheritance

本文关键字:继承 成员      更新时间:2023-10-16

请考虑以下程序:

#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);
}