在函数声明中演绎shared_ptr T.

Chr*_*ger 3 c++ templates shared-ptr c++11

我想写一个看起来像这样的函数:

template<class T>
void Foo(const std::shared_ptr<const T>& ptr);
Run Code Online (Sandbox Code Playgroud)

所以我可以这样称呼它:

std::shared_ptr<int> ptr;
Foo(ptr);
Run Code Online (Sandbox Code Playgroud)

但是,编译器无法推断T,我必须明确它:

Foo<int>(ptr);
Run Code Online (Sandbox Code Playgroud)

或者用它重载void Foo(const std::shared_ptr<T>& ptr).

我可以有一个单一的声明Foo,const T以便T可以推断出来吗?

was*_*ful 10

你的问题是ptr声明为std::shared_ptr<int>while foo需要a std::shared_ptr<const int>.要么ptr使用const限定符声明:

std::shared_ptr<const int> ptr;
Foo(ptr);
Run Code Online (Sandbox Code Playgroud)

或者从声明中删除const限定符foo:

template<class T>
void Foo(const shared_ptr<T>& ptr);
Run Code Online (Sandbox Code Playgroud)

或者,除非你真的需要知道foo你在处理a ,否则shared_ptrfoo真正通用:

template<class T>
void Foo(const T& ptr);
Run Code Online (Sandbox Code Playgroud)