gpt4 book ai didi

c++ - 删除导致模棱两可的过载的转换?

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

我们的代码是多平台的。我使用 MSVC,我的同事使用 Clang 或 GCC。

我们的一个类有一个指针转换,它总是返回非nullptr。我发现了一个问题,因为我不小心在 bool 表达式中使用了它,它总是返回 true。所以,我删除了 bool 转换运算符。

这对我来说非常有效(并且实际上揭示了我们程序中其他十个地方我们正在这样做),但由于模棱两可的重载,我的同事们无法再编译。

情况是这样的:

class Thingy
{
public:
operator const double * () const
{
return xyz;
}

operator bool () const = delete;

private:
double xyz[3];
};

void func(const double *d)
{
}

void func(unsigned int i)
{
}

int main()
{
Thingy a;
func(a);
}

在 MSVC 上,func(const double *d) 被调用,这是我所期望的。但是,在 GCC 上,它失败如下:

<source>: In function 'int main()':
<source>:27:9: error: call of overloaded 'func(Thingy&)' is ambiguous
func(a);
^
<source>:16:6: note: candidate: 'void func(const double*)'
void func(const double *d)
^~~~
<source>:20:6: note: candidate: 'void func(unsigned int)'
void func(unsigned int i)
^~~~
Compiler returned: 1

如果您删除 operator bool () const = delete;,它在 GCC 上工作正常,但您将无法获得以下保护:

Thingy b /* = callSomeFunction()*/;
if (!b)
{
// whoops! never enters here! Would be nice for this to be a compiler error.
}
else
{
// do something with the valid Thingy
}

我们认为在 GCC/Clang 上,歧义在于调用 func(const double*) 并转换为 const double* 和调用 func(unsigned int) 转换为 bool,即使转换为 bool 明确无效。

为什么会这样?为什么 MSVC 允许它?除了 #ifdef _MSVC_VER 之外,还有什么方法可以达到预期的效果吗?

最佳答案

最简单的解决方案是将运算符 bool 声明为 explicit。在 ifwhilefor 中用作条件时,显式运算符将被调用,但对于函数调用的隐式转换将被忽略。

http://coliru.stacked-crooked.com/a/78dd309602295e79

关于c++ - 删除导致模棱两可的过载的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51316116/

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