2016-10-05 39 views
3

我想编写一个函数,看起来像这样:演绎的shared_ptr牛逼

template<class T> 
void Foo(const std::shared_ptr<const T>& ptr); 

,这样我可以这样调用:

std::shared_ptr<int> ptr; 
Foo(ptr); 

然而,编译器不能推演T,我必须明确:

Foo<int>(ptr); 

或与void Foo(const std::shared_ptr<T>& ptr)超载它。

我可以有一个单一的声明Fooconst T,这样T可以推断?

+0

共享指针被设计为复制 - 它是g通常是一个坏主意,通过引用 – UKMonkey

+0

@UKMonkey来传递它们并不完全正确。看到这里http://stackoverflow.com/questions/3310737/shared-ptr-by-reference-or-by-value – Hayt

+0

@Hayt公平 - 就像那里说的,这是选择的问题。我只是点头回去睡觉。 – UKMonkey

回答

10

您的问题是ptr被宣布为std::shared_ptr<int>foo需要std::shared_ptr<const int>。要么你声明ptr用const修饰词:

std::shared_ptr<const int> ptr; 
Foo(ptr); 

或者你从foo声明:移除const属性:

template<class T> 
void Foo(const shared_ptr<T>& ptr); 

或者,除非你真的需要在foo知道你正在处理一个shared_ptr,使foo真正通用:

template<class T> 
void Foo(const T& ptr);