小编Ind*_*ox3的帖子

将 std::shared_ptr<T> 传递给采用 std::shared_ptr<const T> 的函数?

我有一个函数需要共享一个参数的所有权,但不修改它。我已将参数设为 shared_ptr<const T> 以清楚地传达此意图。

template <typename T>
void func(std::shared_ptr<const T> ptr){}
Run Code Online (Sandbox Code Playgroud)

我想将此函数与 shared_ptr 调用到非常量 T。例如:

auto nonConstInt = std::make_shared<int>();
func(nonConstInt);
Run Code Online (Sandbox Code Playgroud)

但是,这会在 VC 2017 上生成编译错误:

error C2672: 'func': no matching overloaded function found
error C2784: 'void func(std::shared_ptr<const _Ty>)': could not deduce template argument for 'std::shared_ptr<const _Ty>' from 'std::shared_ptr<int>'
note: see declaration of 'func'
Run Code Online (Sandbox Code Playgroud)

有没有办法让这项工作没有:

  • 修改对 func 的调用。这是更大的代码重构的一部分,我不想在每个调用站点都使用 std::const_pointer_cast 。
  • 定义 func 的多个重载,因为这似乎是多余的。

我们目前正在根据 C++14 标准进行编译,如果有帮助,我们计划很快迁移到 C++17。

c++ shared-ptr c++11 c++14

9
推荐指数
2
解决办法
379
查看次数

标签 统计

c++ ×1

c++11 ×1

c++14 ×1

shared-ptr ×1