Are explicit conversion operators allowed in braced initializer lists?

后端 未结 3 470
逝去的感伤
逝去的感伤 2021-01-11 09:28

The following code compiles with GCC 4.9.2 but not with Clang 3.5.0:

#include 

class Foo
{
public:
  explicit operator std::string() const;
};         


        
3条回答
  •  逝去的感伤
    2021-01-11 10:02

    clang doesn't seem to care whether the conversion operator is explicit or not, and I believe it is correct due to the wording in [over.best.ics].

    First of all, the direct-initialization

    std::string baz(Foo{});
    

    works on both gcc and clang, and is explained by [class.conv.fct]/2 as mentioned in KerrekSB's answer.

    The direct-list-initialization

    std::string bar{Foo{}};
    

    on the other hand, does not consider any user defined conversions, explicit or not.

    Quoting N3337, §13.3.3.1/4 [over.best.ics]

    However, when considering the argument of a constructor or user-defined conversion function that is a candidate by 13.3.1.3 when invoked for the copying/moving of the temporary in the second step of a class copy-initialization, by 13.3.1.7 when passing the initializer list as a single argument or when the initializer list has exactly one element and a conversion to some class X or reference to (possibly cv-qualified) X is considered for the first parameter of a constructor of X, or by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases, only standard conversion sequences and ellipsis conversion sequences are considered.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题