gpt4 book ai didi

c++ - 私有(private)转换函数导致 "ambiguous default type conversion"错误 (c++)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:22 25 4
gpt4 key购买 nike

首先,一个演示问题的小例子:

struct Bar {
enum Baz {aa, bb, cc};
Baz baz_;

operator Baz() const { return baz_; }
private:
template<typename T> operator T() const;
};

int main() {
Bar bar;
switch (bar) {
case Bar::aa:
break;
case Bar::bb:
break;
case Bar::cc:
break;
default:
break;
}
return 0;
}

使用 g++ 4.7.0 编译此代码会出现以下错误:

foo.cpp: In function ‘int main()’:
foo.cpp:12:16: error: ambiguous default type conversion from ‘Bar’
foo.cpp:12:16: error: candidate conversions include ‘template<class T> Bar::operator T() const’

我的理解是,由于结构对象被“打开”,编译器将尝试找到一个转换为整数或枚举类型的函数。我明确地为 Bar::Baz 枚举类型提供了一个公共(public)转换函数,并希望它使用它。

令我困惑的是,编译器还找到了 private 转换函数,然后无法决定使用哪个。为什么还要考虑私有(private)函数?如果我添加一个显式转换,比如说 switch((int)bar),那么 只有 私有(private)转换函数匹配并且编译器正确地提示它不能使用它,因为它是私有(private)的.那么,既然在这种情况下不能使用私有(private)转换函数,为什么两者之间的选择不明确呢?

有趣的是,我相信(虽然我不是 100% 确定)这段代码在 g++ 4.6 上编译没有错误。

编辑:正如 James McNellis 在评论中指出的那样,私有(private)转换函数是模板化的事实也与此相关。

最佳答案

访问控制在 重载解析之后进行。这是在标准 §13.3 中指定的

Overload resolution is a mechanism for selecting the best function to call given a list of expressions that are to be the arguments of the call and a set of candidate functions that can be called based on the context of the call. The selection criteria for the best function are the number of arguments, how well the arguments match the types of the parameters of the candidate function, how well (for nonstatic member functions) the object matches the implied object parameter, and certain other properties of the candidate function. [Note: the function selected by overload resolution is not guaranteed to be appropriate for the context. Other restrictions, such as the accessibility of the function, can make its use in the calling context ill-formed. ]

因此重载决议可以选择一个不适合给定上下文的函数。

关于c++ - 私有(private)转换函数导致 "ambiguous default type conversion"错误 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10854354/

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