简体   繁体   English

为什么 operator==(std::variant<T, U> , T) 不行吗?

[英]Why does operator==(std::variant<T, U>, T) not work?

Consider the following:考虑以下:

#include <iostream>
#include <variant>

int main ()
{
    std::variant<int, float> foo = 3;
    if(foo == 3)
    {
        std::cout << "Equals 3\n";
    }
}

Godbolt demo here Godbolt 演示在这里

This does not compile because of the foo == 3 :由于foo == 3 ,这不会编译:

<source>:7:12: error: no match for 'operator==' (operand types are 'std::variant<int, float>' and 'int')
    7 |     if(foo == 3)
      |        ~~~ ^~ ~
      |        |      |
      |        |      int
      |        std::variant<int, float>
In file included from /opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/iosfwd:40,
                 from /opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/ios:38,
                 from /opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/ostream:38,
                 from /opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/iostream:39,
                 from <source>:1:
/opt/compiler-explorer/gcc-12.1.0/include/c++/12.1.0/bits/postypes.h:192:5: note: candidate: 'template<class _StateT> bool std::operator==(const fpos<_StateT>&, const fpos<_StateT>&)'
  192 |     operator==(const fpos<_StateT>& __lhs, const fpos<_StateT>& __rhs)
      |     ^~~~~~~~
// Many, many more rejected operator== candidates omitted

There's a free function operator== that compares two std::variant<int, float> s.有一个自由函数operator==比较两个std::variant<int, float> s。 And there's an implicit conversion from int to std::variant<int, float> ;并且有一个从intstd::variant<int, float>的隐式转换; that's how I was able to initialize foo in the first place.这就是我首先能够初始化foo的方式。 So why doesn't this comparison compile?那么为什么这个比较不编译呢?

Strictly speaking, I suppose there are a few related questions here.严格来说,我想这里有几个相关的问题。 One is why this doesn't already work, explaining how the rules for overload resolution apply to this section.一个是为什么这还不起作用,解释重载解决的规则如何适用于本节。 And second is if there's anything that can be done in user-written code to make this comparison work sensibly.其次是是否可以在用户编写的代码中做任何事情来使这种比较合理地工作。

Neither parameter of that operator== overload is an undeduced context.operator==重载的两个参数都不是未推断的上下文。 So template argument deduction for the overload will fail if it fails in either parameter/argument pair.因此,如果在任一参数/参数对中失败,则重载的模板参数推导将失败。

Since int is not a std::variant , deduction will fail for the corresponding parameter/argument pair and so the template overload is not viable.由于int不是std::variant ,因此相应参数/参数对的推导将失败,因此模板重载不可行。

Implicit conversions are not considered when deducing template arguments.推导模板参数时不考虑隐式转换。 Types must (with few minor exceptions) match exactly.类型必须(除了少数小例外)完全匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM