【问题标题】:Why aren't operator conversions implicitly called for templated functions? (C++)为什么不为模板化函数隐式调用运算符转换? (C++)
【发布时间】:2010-04-19 17:39:42
【问题描述】:

我有以下代码:

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

当我使用 gcc 4.3.3 编译代码时,我收到一条消息 (aaa.cc:17: error: no matching function for call to ‘tf(pointer&lt;float&gt;&amp;)’),表明编译器为非模板函数 f() 调用了 'operator pointer&lt;const T&gt;',但没有为模板函数 tf( )。为什么以及是否有任何解决方法不使用 const 和非 const 版本重载 tf()?

提前感谢您的帮助。

【问题讨论】:

  • 也许 stackoverflow 软件正在删除您的模板尖括号?

标签: c++ templates implicit


【解决方案1】:

原因是你在模板推导期间没有得到隐式类型转换,它永远不会到达那个点。

考虑:

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】:
template <typename U>
void tf(pointer<const float>);

^ 除非您在函数调用中明确指定参数类型,否则编译器不会匹配对该函数的函数调用,因为您不使用类型名 U 作为函数参数。我怀疑你想做这样的事情:

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

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2016-06-01
    • 1970-01-01
    • 2022-10-02
    • 1970-01-01
    • 2012-02-11
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多