代码之家  ›  专栏  ›  技术社区  ›  Hong Jiang

C++模板与隐式转换

c++
  •  4
  • Hong Jiang  · 技术社区  · 17 年前

    我有以下代码:

    #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;
    }
    

    我觉得很奇怪 call_base_print(gchild) call_print(gchild) 导致编译器错误。我知道C++不允许两个隐式转换,但我不认为这里有两个转换。有谁能启发我吗?

    2 回复  |  直到 17 年前
        1
  •  5
  •   MSalters    17 年前

    你没有达到类型转换的程度。它在前面的模板实例化中失败。

    call_base_print call_print<T>(shared_ptr<Child<T> > a) 做你在通过一个考试 shared_ptr<GrandChild> . 没有什么可以替代的 shared_ptr<Child<T> > 共享\u ptr<孙辈> . 因此,实例化失败,并且没有可调用的函数。

        2
  •  0
  •   xtofl Adam Rosenfield    17 年前

    你认为 shared_ptr<GrandChild> 源于 shared_ptr<Child> call_print 需要的参数类型与您提供的参数类型不同。

    另一个警告:即使存在从子类到超类的转换,也会导致子类对象的切片,因为您按值提供参数。

    通过使用指针参数i.s.o,您可以获得您想要的行为。 shared_ptr