【发布时间】:2023-03-11 07:59:01
【问题描述】:
我正在尝试将模板参数推导与继承和std::shared_ptr 结合使用。正如您在下面的示例代码中看到的,我将shared_ptr<Derived> 传递给一个模板化的非成员函数,该函数应该进行模板参数推导。如果我手动命名类型一切正常,如果我让它做模板参数推导它就不行。 似乎编译器似乎无法确定类型,但错误消息显示它确实如此。我不确定这里发生了什么,如果有任何意见,我将不胜感激。 (Visual Studio 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>
【问题讨论】:
-
这是 GCC 4.7.3 对此的评价,仅供参考:
t.cpp:9:6: note: template argument deduction/substitution failed: t.cpp:16:47: note: mismatched types 'Base<T>' and 'Derived' t.cpp:16:47: note: 'std::shared_ptr<Derived>' is not derived from 'std::shared_ptr<Base<T> >'
标签: c++ templates inheritance c++11 smart-pointers