【发布时间】:2020-11-26 17:50:39
【问题描述】:
我有一个函数需要共享一个参数的所有权,但不修改它。
我已将参数设为 shared_ptr
template <typename T>
void func(std::shared_ptr<const T> ptr){}
我想用 shared_ptr 将这个函数调用为非常量 T。例如:
auto nonConstInt = std::make_shared<int>();
func(nonConstInt);
但是这会在 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'
有没有办法让这项工作没有:
- 修改对 func 的调用。这是更大的代码重构的一部分,我不希望在每个调用站点都使用 std::const_pointer_cast。
- 定义多个 func 重载似乎是多余的。
我们目前正在根据 C++14 标准进行编译,如果有帮助,我们计划很快迁移到 C++17。
【问题讨论】:
-
我认为模板的优先级更高,如果这将是完全输入的,它就可以工作。您可以添加一个重载,尽管这没有多大意义。只是为了确定,你需要一个 shared_ptr 而不是参考?
-
是的,如果 func 不是模板,它就可以工作(这就是为什么我很惊讶它不适用于模板函数)。 func 正在共享指向对象的所有权,所以我不能引用 T。
-
Goh,预见将 const 添加到 shared_ptr 的免费方法将是我的实用解决方案,或者添加 2 个重载并在重定向之前显式添加 const。
标签: c++ c++11 c++14 shared-ptr