3

I want to write a function that looks like this:

template<class T>
void Foo(const std::shared_ptr<const T>& ptr);

so that I can call it like this:

std::shared_ptr<int> ptr;
Foo(ptr);

However, the compiler can't deduce T and I have to make it explicit:

Foo<int>(ptr);

or to overload it with void Foo(const std::shared_ptr<T>& ptr).

Can I have a single declaration Foo with const T so that T can be deduced?

rocambille
  • 15,398
  • 12
  • 50
  • 68
ChronoTrigger
  • 8,459
  • 1
  • 36
  • 57
  • Shared pointers are designed to be copied - it's generally a bad idea to pass them around by reference – UKMonkey Oct 05 '16 at 10:59
  • @UKMonkey that is not exactly right. See here http://stackoverflow.com/questions/3310737/shared-ptr-by-reference-or-by-value – Hayt Oct 05 '16 at 11:03
  • @Hayt Fair enough - as said there, it's matter of option. I'll just nod and go back to sleep. – UKMonkey Oct 05 '16 at 11:10
  • @UKMonkey that's why I did not say you were wrong ;) it's just not black and white on this topic – Hayt Oct 05 '16 at 11:12

1 Answers1

10

Your problem is that ptr is declared as std::shared_ptr<int> while foo requires a std::shared_ptr<const int>. Either you declare ptr with the const qualifier:

std::shared_ptr<const int> ptr;
Foo(ptr);

Or you remove the const qualifier from the declaration of foo:

template<class T>
void Foo(const shared_ptr<T>& ptr);

Or, unless you really need to know in foo that you are dealing with a shared_ptr, make foo truly generic:

template<class T>
void Foo(const T& ptr);
rocambille
  • 15,398
  • 12
  • 50
  • 68