代码之家  ›  专栏  ›  技术社区  ›  John Gordon

为什么不隐式调用模板化函数的运算符转换?(C++)

  •  7
  • John Gordon  · 技术社区  · 14 年前

    我有以下代码:

    template <class T>
    struct pointer
    {
      operator pointer<const T>() const;
    };
    
    
    void f(pointer<const float>);
    
    template <typename U>
    void tf(pointer<const U>);
    
    void g()
    {
      pointer<float> ptr;
      f(ptr);
      tf(ptr);
    }
    

    当我使用GCC4.3.3编译代码时,我得到一条消息( aaa.cc:17: error: no matching function for call to ‘tf(pointer<float>&)’ )指示编译器调用 'operator pointer<const T>' 对于非模板化函数f(),但对于模板化函数t f()则不是。为什么,除了使用const和non-const版本重载tf()之外,还有什么解决方法吗?

    事先谢谢你的帮助。

    2 回复  |  直到 14 年前
        1
  •  6
  •   GManNickG    14 年前

    原因是在模板推导过程中,您没有得到隐式类型转换,它永远不会达到这一点。

    考虑:

    template <typename T>
    struct foo {};
    
    template <typename U>
    void bar(foo<U>)
    {}
    
    foo<int> f;
    bar(f);
    

    对于对bar的调用,编译器可以推断出 U 是一个 int ,并实例化函数。但是,考虑:

    template <typename U>
    void bar(foo<const U>)
    {}  // note  ^^^^
    
    foo<int> f;
    bar(f);
    

    没有 U 编译器可以推断出 foo 匹配参数的类型。因此,模板实例化失败。转换是不可能发生的。

        2
  •  1
  •   Charles Salvia    14 年前
    template <typename U>
    void tf(pointer<const float>);
    

    ^除非在函数调用中显式指定参数类型,否则编译器将不匹配对此函数的函数调用,因为您不使用类型名 U 作为函数参数。我怀疑你想做如下的事情:

    template <typename U>
    void tf(pointer<U>);