【问题标题】:User-defined conversion operator template and built-in operators: no match for operator自定义转换运算符模板和内置运算符:运算符不匹配
【发布时间】:2018-09-14 03:15:53
【问题描述】:

考虑以下 MCVE。

#include <type_traits>

struct A {
    template<typename T, typename std::enable_if<std::is_same<T,int>::value,int>::type = 0>
    operator T() const { return static_cast<T>(1); }
};

int main() {
    int x = 1;
    A a;
    return x + a;
}

clang 编译得很好。 DEMO

GCC 失败:

error: no match for 'operator+' (operand types are 'int' and 'A')
  return x + a;
         ~~^~~

问题:谁是对的,为什么?

【问题讨论】:

    标签: c++ c++11 language-lawyer


    【解决方案1】:

    我相信 clang 是对的。

    要查找+,因为至少有一个参数具有类类型,所以我们考虑member, non-member, and builtin candidates。没有任何成员或非成员候选人,所以这就足够了。 int operator+(int, int) 有一个内置的候选者,这是唯一的候选者。该候选是可行的,因为A 可以直接转换为int(对于隐式对象参数,我们有一个从Aconst A&amp; 的标准转换,然后是用户定义的从该到int 的转换,无需进一步转换)。由于我们有一个可行的候选者,因此它很容易成为最可行的候选者。


    请注意,如果A 只是有operator int() const { return 1; },gcc 会接受它。只是转换函数template没有考虑。

    【讨论】:

      猜你喜欢
      • 2011-04-10
      • 1970-01-01
      • 2018-07-19
      • 2012-03-12
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      相关资源
      最近更新 更多