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?
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);