c++ - 在函数声明中推导 shared_ptr T

标签 c++ templates c++11 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可以推导出来吗?

最佳答案

你的问题是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);

关于c++ - 在函数声明中推导 shared_ptr T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39872033/

相关文章:

c++ - 有没有一种简单的方法可以在 C++0x 中实现 AutoResetEvent?

c++ - 将 C++ 声明标记为已弃用的可移植方法,将被 C++ 11 接受

c++ - 编译时接口(interface)定义的最佳实践

c++ - 从模板函数返回 double 或 complex<double>

c++ - 使用 is_same_v 自动类型推导

c++ - 从内部类引用模板

c++ - 理解 ask --true 0 不是数字 0

c++ - 为什么按位否定运算符 "~"转换为 int? (从 ‘unsigned char’ 转换为 ‘int’ 可能会改变它的值)

c++ - 为什么 "int & const"使用 MSVC 可以正常编译?

C++11右值引用题