【发布时间】:2019-05-27 09:21:02
【问题描述】:
这是我的 C++ 程序代码
#include <iostream>
#include <memory>
using namespace std;
template <typename T>
struct A { T x; };
template <typename T>
struct B:A<T> { };
template <typename T>
void func(const A<T>& t) {
cout<<"2"<<endl;
}
template <typename T>
void func(const T& t) {
cout<<"1"<<endl;
}
int main() {
B<int> b;
func(b);
}
它会打印出1。但我期望的是函数调用打印2。为什么B<int>b 匹配const T& 而不是const A<T>&。我怎样才能使它匹配到const A<T>&?
【问题讨论】:
-
对于
void func(const T& t),T推导出为B<int>。void func(const B<int>& t)比void func(const A<int>& t)更匹配。 -
我应该更改什么以使其与
void func(const A<int>& t)匹配? -
您可以为每个派生类编写一个代理重载,例如
template <typename T> void func(const B<T> &t) {func(static_cast<const A<T> &>(t));}。这听起来有道理吗? -
所有派生类是否都遵循相同的模式:
template <typename T> struct Derived : A<T>? -
谢谢,您的建议在这种情况下会有所帮助。
A<T>有很多子类。在我的程序中,有很多地方像template<typename T1, typename T2> void func2(const A<T1>&p1, const A<T2>&p2)。如果我使用代理重载,由于笛卡尔积必须编写许多代理重载。