【发布时间】:2016-10-23 18:33:47
【问题描述】:
问题是代码。看起来第二个功能比第一个更特别。为什么在下面的代码中调用更通用的?我怎样才能使其他功能被使用?
template <typename T>
class Base{
public:
Base(){}
void print() const {cout<<"Base class"<<endl;}
};
template <typename T>
class Derived :public Base<T>{
public:
Derived() {}
void print() const {cout<<"Derived class"<<endl;}
};
template <typename T>
void func(T x){ // <----- Why is function is called?
x.print();
cout<<"in func(T)"<<endl;
}
template <typename T>
void func(const Base<T>& x){
x.print();
cout<<"in func(Base<T>)"<<endl;
}
int main () {
Base<int> b;
Derived<int> d;
func(d);
return 0;
}
请注意,我将 Derived 对象传递给函数。
【问题讨论】:
-
这篇文章可以帮助你:stackoverflow.com/questions/22411482/…。请参阅@NikosAthanasiou 的答案。
标签: c++ templates overloading overload-resolution