成员模板和继承

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,即使 override 关键字被 g++ 接受(我认为这是一个错误)。

虽然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);
}