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_ptr
要foo
真正通用:
template<class T>
void Foo(const T& ptr);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
112 次 |
最近记录: |