C++ templates and implicit type conversion

c++

Solution

You don't get to the point of type conversion. It fails earlier, in template instantiation.

`call_base_print` doesn't require type deduction. `call_print<T>(shared_ptr<Child<T> > a)` does. You're passing a `shared_ptr<GrandChild>`. And there's simply no T you can substitute such that `shared_ptr<Child<T> >` is `shared_ptr<GrandChild>`. Therefore, instantiation fails, and there is no function to call.

Problem

I have the following code: ``` #include <iostream> #include "boost/shared_ptr.hpp" using boost::shared_ptr; class Base { public: virtual ~Base() {} virtual void print() = 0; }; template <typename T> class Child : public Base { public: virtual void print() { std::cout << "in Child" << std::endl; } }; class GrandChild : public Child<int> { public: virtual void print() { std::cout << "in GrandChild" << std::endl; } }; template <typename T> void call_print(shared_ptr<Child<T> > a) { a->print(); } void call_base_print(shared_ptr<Base> a) { a->print(); } int main() { shared_ptr<GrandChild> gchild(new GrandChild); call_print(shared_ptr<Child<int> >(gchild)); // call_print(gchild); // Cannot compile! call_base_print(gchild); // This works. return 0; } ``` I found it strange that `call_base_print(gchild)` works but `call_print(gchild)` causes a compiler error. I know that C++ does not allow two implicit conversions, but I don't think there're two conversions here... Could anyone enlighten me?

Original source

Related problems