C++ 在派生类中重载模板函数

标签 c++ templates

我知道您可以根据模板参数重载模板:

template <class T> void test() {
    std::cout << "template<T>" << std::endl;
}
void test() {
    std::cout << "not a template" << std::endl;
}

然后在一些函数中:

test<int>();
test();

将正确解析您想要的 2 个不同版本的 test() 中的哪一个。但是,如果我现在在具有继承的类中执行此操作:

class A {
public:
    void test() {
       std::cout << "A::Test: not a template" << std::endl;
    }
};
class B : public A {
public:
    template <class T>
    void test() {
       std::cout << "B::Test: template<T>" << std::endl;
    }
};

然后在函数内部:

B b;
b.test<int>();
b.test();

b.test<int>();有效,但是 b.test();不:

error: no matching function for call to ‘B::test()’
note: candidate is:
note: template<class T> void B::test()

为什么会这样/有没有办法让它根据模板参数正确解析两个版本?

最佳答案

与往常一样,派生类中定义的名称会隐藏基类中相同名称的使用。要将基类中的名称提升到派生类中,请添加

using A::test;

到派生类。

关于C++ 在派生类中重载模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12146919/

相关文章:

C++ Boost 变体错误

c++ - 为不需要专门化的 double 和 std::complex 创建函数模板

c++ - C++中 'glue'两个类实现的正确方法

c++ - 使用模板的运算符重载赋值 - C++

css - 使两个CSS类相同

c++ - 自定义排序和映射时更喜欢函数指针还是函数对象?

c++ - 使用 Visual Studio 2015、C++ 项目的 DLL 没有 "Copy to Output Directory"

c++ - 如何用 C++ 编写 "meta if else if.."?

c++ - 需要一些帮助解决两个错误 (C++)

django - 问题在django admin中扩展了change_form.html