为什么是“operator void”不是使用转换语法调用? [英] Why is "operator void" not invoked with cast syntax?

查看:113
本文介绍了为什么是“operator void”不是使用转换语法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此回答用户GMan 制作了以下代码段(使用Visual C ++ 9编译):



While playing with this answer by user GMan I crafted the following snippet (compiled with Visual C++ 9):

 class Class {
 public:
     operator void() {}
 };

 Class object;
 static_cast<void>( object );
 (void)object;
 object.operator void();

我发现转换到 void 不调用 Class :: operator void(),只有第三次调用(显式调用操作符)实际调用操作符,

after stepping over with the debugger I found out that casting to void doesn't invoke Class::operator void(), only the third invokation (with explicitly invoking the operator) actually invokes the operator, the two casts just do nothing.

为什么运算符void 未使用转换语法调用?

Why is the operator void not invoked with the cast syntax?

推荐答案

在§12.3.2中找到的技术原因:

The technical reason why is found in §12.3.2:


转换函数从不用于将(可能是cv限定的)对象转换为(可能是cv限定的)同一对象类型(或对其的引用),转换为该类型的(可能是cv限定的)基类(或其引用)或(可能是cv限定的)void

(可能)允许§5.2.9/ 4工作:

The rationale is (likely) to allow §5.2.9/4 to work:


任何表达式都可以显式转换为类型cv void。将舍弃表达式值。

Any expression can be explicitly converted to type "cv void." The expression value is discarded.

(void)expr 没有任何任何表达式的结果值,但如果它调用您的转换操作符,它不会丢弃任何东西。因此,他们禁止在转换中使用 operator void

(void)expr to suppose to do nothing for the resulting value of any expression, but if it called your conversion operator it wouldn't be discarding anything. So they ban the use of operator void in conversions.

为什么不让转换类型ID为 void 的形式不合格?谁知道,但请记住,这不是完全无用的:

Why not make it ill-formed to have the conversion-type-id be void? Who knows, but keep in mind it's not totally useless:

struct foo
{
    operator void()
    {
        std::cout << "huh?" << std::endl;
    }

};

typedef void (foo::*void_function)();

foo f;
void_function func = &foo::operator void;

(f.*func)(); // prints "huh"
f.operator void(); // also does (which you knew)

/ em>,所以也许这是合理的,不能使它不成形。

It is still technically potentially useful for something, so maybe that's rationale enough not to make it ill-formed.

这篇关于为什么是“operator void”不是使用转换语法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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