gpt4 book ai didi

c++ - 用户定义的转换函数和转换为引用

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:06 25 4
gpt4 key购买 nike

我遇到以下代码的编译错误:

class SymbolGroup
{
std::string d_;

public:
SymbolGroup(std::string a):d_(a){}

// explicit operator const std::string&() const { return d_;} // compiles
explicit operator std::string() const { return d_;} // Does not compile
};

inline
bool operator==(const SymbolGroup& lhs, const SymbolGroup& rhs)
{
return static_cast<const std::string&>(lhs) ==
static_cast<const std::string&>(rhs);
}

int main(){

SymbolGroup a("hello");
SymbolGroup b("hello");

if (a==b)
std::cout << "they are the same\n";

return 0;
}

如果用户定义类型转换行中没有 'const' 和 '&',它不会在带有 --std=c++11 标志的 g++ (4.8) 中编译:

error: invalid initialization of reference of type ‘std::string& {aka std::basic_string&}’ from expression of type ‘const string {aka const std::basic_string}’ explicit operator std::string&() const { return d_;}

代码在 Clang 上以两种方式编译。哪个编译器是正确的?这段代码应该用 operator std::string() 编译吗?

最佳答案

更新 我之前的回答是完全错误的。道歉! tldr; clang 接受代码是正确的,gcc 拒绝它是不正确的。


首先,来自 [expr.static.cast]:

An expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5).

我们尝试直接初始化 std::string const& 类型的对象非常有效显式来自 SymbolGroup const& 类型的对象.有一个部分专门介绍通过转换函数初始化引用:“Initialization by conversion function for direct reference binding”[over.match.ref]:

Under the conditions specified in 8.5.3, a reference can be bound directly to a glvalue or class prvalue that is the result of applying a conversion function to an initializer expression. Overload resolution is used to select the conversion function to be invoked. Assuming that “cv1 T” is the underlying type of the reference being initialized, and “cv S” is the type of the initializer expression, with S a class type, the candidate functions are selected as follows:

— The conversion functions of S and its base classes are considered. Those non-explicit conversion functions that [...] are candidate functions. For direct-initialization, those explicit conversion functions that are not hidden within S and yield type “lvalue reference to cv2 T2” or “cv2 T2” or “rvalue reference to cv2 T2”, respectively, where T2 is the same type as T or can be converted to type T with a qualification conversion (4.4), are also candidate functions.

第一部分不适用,因为我们的转换函数是 explicit ,所以我省略了。第二部分确实如此。我们有 cv1 T 是 const std::string , 所以我们的转换函数为 std::string是候选函数,因为 std::string可以转换为const std::string与资格转换。


这里gcc错了,我提交了bug 66893 ,由我们自己的 C++ 专家和周围的好人确认 Jonathan Wakely以及首席 Clang 开发人员和 C++ 标准编辑 Richard Smith(在我彻底尴尬地提交 Clang 错误之后)。

关于c++ - 用户定义的转换函数和转换为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31428980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com