支持的初始化器列表中是否允许显式转换操作符? [英] Are explicit conversion operators allowed in braced initializer lists?

查看:184
本文介绍了支持的初始化器列表中是否允许显式转换操作符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使用GCC 4.9.2编译,但不与Clang 3.5.0一起编译:

  #include< string& 

类Foo
{
public:
显式运算符std :: string()const;
};

std :: string bar {Foo {}}; //在g ++中工作,在clang中失败++
std :: string baz(Foo {}); // works in both

clang ++说:

  foo.cpp:9:13:错误:没有匹配的构造函数初始化'std :: string'
(aka'basic_string< char>')
std :: string bar {Foo {}};
^ ~~~~~~~
...:注意:候选构造函数不可行:没有已知的从'Foo'到
的转换const std :: basic_string< char> &'for 1st argument
basic_string(const basic_string& __str);奇怪的是,如果 std :: string / code>替换为 int 之类的原始类型。

解决方案

这似乎是一个ang错误。 [over.match.list] / 1:


当非聚合类类型 T 是列表初始化
(8.5.4),重载解决方案在两个阶段选择构造函数:




  • ..]

  • 如果没有找到可行的初始化列表构造函数,则再次执行重载解析,其中候选函数都是
    类的构造函数<$


/ blockquote>

由于第二行编译正确,因此存在不一致:当涉及重载解析时,它们应该是等效的。


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

#include <string>

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

std::string bar{Foo{}}; // Works in g++, fails in clang++
std::string baz(Foo{}); // Works in both

clang++ says:

foo.cpp:9:13: error: no matching constructor for initialization of 'std::string'
      (aka 'basic_string<char>')
std::string bar{Foo{}};
            ^  ~~~~~~~
...: note: candidate constructor not viable: no known conversion from 'Foo' to
      'const std::basic_string<char> &' for 1st argument
      basic_string(const basic_string& __str);
      ^

Curiously, it works if std::string is replaced with a primitive type like int.

解决方案

This seems to be a Clang bug. [over.match.list]/1:

When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases:

  • [..]
  • If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.

Since the second line compiles fine, there is an inconsistency: They should be equivalent when it comes to overload resolution.

这篇关于支持的初始化器列表中是否允许显式转换操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆