c++ - Deduce weak_ptr argument from shared_ptr -
the following gives me compiler error:
could not deduce template argument 'const std::weak_ptr<_ty> &' 'std::shared_ptr'
#include <memory> class foo { public: template<typename r> void bar(std::weak_ptr<r> const & p) { p; } }; int main(void) { auto foo = foo(); auto integer = std::make_shared<int>(); foo.bar(integer); } i tried,
template<typename r> void bar(std::weak_ptr<r::element_type> const & p) { } , seems syntatically incorrect. following works wondered if it's possible conversion in p, without creating temporary?
template<typename r> void bar(r const & p) { auto w = std::weak_ptr<r::element_type>(p); } to clear i'd explicitly state function should take shared or weak_ptr, don't r const & p solution.
for completeness works of course:
template<typename r> void bar(std::shared_ptr<r> const & p) { auto w = std::weak_ptr<r>(p); }
the template parameter r of std::weak<r> cannot deduced instance of std::shared_ptr<a> because converting constructor (which takes std::shared_ptr<y>) constructor-template meansy — , there no way deduce r y (which deduced a). have @ converting constructor.
you write this:
template<typename t> auto make_weak(std::shared_ptr<t> s) -> std::weak_ptr<t> { return { s }; } then call as:
foo.bar( make_weak(integer) );
Comments
Post a Comment