【问题标题】:Visual C++ - call conversion operator on a primitive type explicitlyVisual C++ - 显式调用基本类型的转换运算符
【发布时间】:2015-06-29 18:30:29
【问题描述】:

我在玩一个类Foo,它定义了一个隐含的operator bool()。我使用Foo 作为多个函数的返回类型,因此我可以获得有关已完成操作的信息并调用Foo::operator bool() 以获取操作是否已成功执行。

出于好奇,我还尝试在使用Foo时显式调用转换运算符:

if(!func().operator bool()) // func returned Foo
    throw std::logic_error("operation was not successful");

效果很好。然后,我突然决定转储Foo 类并使用简单的bool,但我忘记删除函数返回值上的.operator bool() 调用。于是我发现了 Visual C++ 12.0 编译器(Visual Studio 2013)的一组奇怪行为。


转换运算符对bool 的显式调用在 GCC 中均无效:
request for member ‘operator bool’ in ‘true’, which is of non-class type ‘bool’

现在,我使用 Visual Studio 得到的行为:

#include <iostream>
using std::cout;
using std::endl;

bool func()
{
    return true;
}

int main()
{
    bool b = true.operator bool();
    cout << b << endl; // error C4700: uninitialized local variable 'b' used

    // evaluates to true (probably like b would do if it compiled)
    if(false.operator bool())
        cout << "a" << endl;

    cout << func().operator bool() << endl; // prints nothing

    int m = 10;
    cout << m.operator int() << endl; // prints nothing

    // correctly gives error: left of '.<' must have class/struct/union
    cout << m.operator <(10) << endl;
}

即使是智能感知也是正确的并显示Error: expression must have a class type。 这一切有解释吗?一个错误? (不需要的)扩展?这是什么?

【问题讨论】:

  • 不应该编译,并且可能是编译器中的一个错误。从纯语法的角度来看,代码是正确的,但语义不正确,应该会导致错误。
  • 没什么here
  • 废话统治:bool b = false.operator int; 被很好地接受。而 b 是 true :)
  • 最奇怪的是你有一个明确的.operator bool() 忘记删除放在首位
  • Visual C++ 2015 CTP6 中也存在同样的奇怪行为。您应该在Connect 上报告此问题。

标签: c++ visual-c++ visual-studio-2013 operators


【解决方案1】:

很好的发现!该标准肯定会使这种格式不正确,需要进行诊断,[expr.ref]:

后缀表达式后跟点. 或箭头-&gt;, 可选地后跟关键字template (14.2),然后 后面跟着一个id-expression,是一个后缀表达式。 [..] 对于 第一个选项(点)第一个表达式应具有完整的类 输入。

另外,不是扩展:将是一个非常荒谬的扩展。看来VC++实现了bool和一些internal (class-like?) type

在 Visual C++ 5.0 及更高版本中,bool 被实现为内置类型 大小为 1 个字节。

该类型的类语义显然没有被完全抑制。甚至

bool b;
b.operator std::string();

编译(giving a seemingly empty string),暗示内部类有一个转换运算符模板。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多