将std::shared_ptr<T>传递给采用std::shared_ptr<constT>的函数?
我有一个函数需要共享一个参数的所有权,但不修改它。我已将参数设为 shared_ptr<const T> 以清楚地传达此意图。
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。
回答
template <typename T>
void cfunc(std::shared_ptr<const T> ptr){
// implementation
}
template <typename T>
void func(std::shared_ptr<T> ptr){ return cfunc<T>(std::move(ptr)); }
template <typename T>
void func(std::shared_ptr<const T> ptr){ return cfunc<T>(std::move(ptr)); }
这与cbegin工作方式相匹配,并且“过载”是几乎零成本的琐碎转发器。
THE END
二维码