成员模板和继承

时间:2015-03-08 09:28:08

标签: c++ templates 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);
}

谢谢

1 个答案:

答案 0 :(得分:2)

你可以像这样明确地调用成员函数模板(或者更确切地说:由它构成的成员函数):

void f(const T &x) override {
    f<T>(x);
}
相关问题