c++ - 为什么不使用强制转换语法调用 "operator void"?

标签 c++ casting operators operator-overloading

在玩 this answer 时通过 user GMan我制作了以下代码片段(使用 Visual C++ 9 编译):

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

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

通过调试器后,我发现转换为 void 不会调用 Class::operator void(),只有第三次调用(显式调用运算符)实际上调用了运算符,这两个转换什么都不做。

为什么 operator void 没有用强制转换语法调用?

最佳答案

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

A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.

基本原理是(可能)允许 §5.2.9/4 工作:

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

(void)expr 假设对 any 表达式的结果值不做任何事情,但如果它调用你的转换运算符,它就不会丢弃任何东西。所以他们禁止在转换中使用 operator void


为什么不使转换类型 ID 为 void 格式错误?谁知道呢,但请记住它并非完全没用:

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)

它在技术上仍然对某些东西有用,所以也许这足以使它的格式不正确。

关于c++ - 为什么不使用强制转换语法调用 "operator void"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30532566/

相关文章:

c++ - 为什么制作 const 函数很有用?

c++ - 列出 n 个对象的所有 k-排列的有效方法,同时满足特定标准

c# - 将未知对象转换为接口(interface)的泛型接口(interface)(从最初明确的泛型类型到泛型集合类型的类型)

c - 将 double 转换为 int 时出错

c# - 为什么模运算符 (%) 结果在 C# 中隐式转换到左侧而不是右侧?

c++ - 排序时堆栈溢出(合并排序和快速排序)

c++ - std::copy 和容器的复制构造函数之间是否存在任何性能差异?

java - 从 int 创建时钟格式

javascript - 使用下拉框更改运算符来操作输入框

ruby - 了解 Ruby 中 If 条件中的 "||"OR 运算符