我有一个函数需要共享一个参数的所有权,但不修改它。我已将参数设为 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)
有没有办法让这项工作没有:
我们目前正在根据 C++14 标准进行编译,如果有帮助,我们计划很快迁移到 C++17。