我正在尝试将模板参数推导与继承和std::shared_ptr
. 正如您在下面的示例代码中所见,我将 a 传递shared_ptr<Derived>
给模板化的非成员函数,该函数应该执行模板参数推导。如果我手动命名类型一切正常,如果我让它做模板参数推导它就不行。编译器似乎无法确定类型,但错误消息显示它确实如此。我不确定这里发生了什么,如果有任何意见,我将不胜感激。(视觉工作室 2010)
#include <memory>
template <typename T>
class Base {};
class Derived : public Base<int> {};
template <typename T>
void func(std::shared_ptr<Base<T> > ptr) {};
int main(int argc, char* argv[])
{
std::shared_ptr<Base<int>> myfoo(std::shared_ptr<Derived>(new Derived)); // Compiles
func(myfoo); // Compiles
func<int>(std::shared_ptr<Derived>(new Derived)); // Compiles
func(std::shared_ptr<Derived>(new Derived)); // Doesn't compile. The error message suggests it did deduce the template argument.
return 0;
}
错误信息:
5> error C2664: 'func' : cannot convert parameter 1 from 'std::tr1::shared_ptr<_Ty>' to 'std::tr1::shared_ptr<_Ty>'
5> with
5> [
5> _Ty=Derived
5> ]
5> and
5> [
5> _Ty=Base<int>
5> ]
5> Binding to reference
5> followed by
5> Call to constructor 'std::tr1::shared_ptr<_Ty>::shared_ptr<Derived>(std::tr1::shared_ptr<Derived> &&,void **)'
5> with
5> [
5> _Ty=Base<int>
5> ]
5> c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\memory(1532) : see declaration of 'std::tr1::shared_ptr<_Ty>::shared_ptr'
5> with
5> [
5> _Ty=Base<int>
5> ]
5>