jeudi 26 novembre 2020

Passing a std::shared_ptr

I have a function that needs to take shared ownership of an argument, but does not modify it. I have made the argument a shared_ptr<const T> to clearly convey this intent.

template <typename T>
void func(std::shared_ptr<const T> ptr){}

I would like to call this function with a shared_ptr to a non-const T. For example:

auto nonConstInt = std::make_shared<int>();
func(nonConstInt);

However this generates a compile error on 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'

Is there a way to make this work without:

  • Modifying the calls to func. This is part of a larger code refactoring, and I would prefer not to have to use std::const_pointer_cast at every call site.
  • Defining multiple overloads of func as that seems redundant.

We are currently compiling against the C++14 standard, with plans to move to c++17 soon, if that helps.

Aucun commentaire:

Enregistrer un commentaire