【发布时间】:2015-04-14 17:11:58
【问题描述】:
以下给我编译器错误:
无法推导出 'const std::weak_ptr<_ty> &' 的模板参数 来自'std::shared_ptr'
#include <memory>
class Foo
{
public:
template<typename R>
void Bar(std::weak_ptr<R> const & p)
{
p;
}
};
int main(void)
{
auto foo = Foo();
auto integer = std::make_shared<int>();
foo.Bar(integer);
}
我试过了,
template<typename R>
void Bar(std::weak_ptr<R::element_type> const & p)
{
}
,这似乎在语法上不正确。以下工作,但我想知道是否有可能在 p 中进行转换,而不创建另一个临时?
template<typename R>
void Bar(R const & p)
{
auto w = std::weak_ptr<R::element_type>(p);
}
为了清楚起见,我想明确声明该函数应该采用 shared 或 weak_ptr,所以我不喜欢 R const & p 解决方案。
为了完整起见,这当然也可以:
template<typename R>
void Bar(std::shared_ptr<R> const & p)
{
auto w = std::weak_ptr<R>(p);
}
【问题讨论】:
-
element_type 是 shared_ptr (trait) 的类型。在这种情况下,
是一个 shared_ptr 。至少这似乎是类型推断过程告诉我的。所以在示例中 element_type 将是“int”。
标签: c++ shared-ptr weak-ptr