我知道您可以根据模板参数重载模板:
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/