为什么不可能有无效参考? [英] Why is it impossible to have a reference-to-void?

查看:85
本文介绍了为什么不可能有无效参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不可能引用void?我在C ++标准中发现的唯一内容是以下行,位于 8.3.2.1

Why is it impossible to have a reference to void? The only thing I found in the C++ Standard is this line, at 8.3.2.1


类型对 cv void的引用格式错误。

A declarator that specifies the type "reference to cv void" is ill-formed.

为什么这样呢?为什么我不能编写一个接受 void& 的通用函数?

Why is it that way? Why can't I write a "generic" function that accept a void&?

只是要清楚一点,我没有想到有用的应用程序,在这种情况下,使用void引用比使用模板要好,但是我只是对此感到好奇

Just to be clear, I have no useful application in mind where using a reference-to-void could be better than using templates, but I'm just curious about the rationale for forbidding this construct.

为了澄清一点,我理解使用空引用是这样与取消引用空指针一样没有意义。但是,我可以将其转换为对 sometype 的引用才能使用,不是吗?实际上,我不明白为什么以下代码段可以工作...

To clarify a little, I understand that using a reference-to-void "as is" would be as meaningless as dereferencing a pointer-to-void. However, I could cast it to a reference-to-sometype in order to use it, couldn't I? In fact, I don't see why the following snippet can work...

void foo(void *data)
{
    int *i = reinterpret_cast<int*>(data);
    // do something with i
}

...而这一个不能:

...while this one cannot:

void foo(void &data)
{
    int &i = reinterpret_cast<int&>(data);
    // do something with i
}


推荐答案

如果您确实引用过void,那么您将如何处理它?它不是数字,字符,指针或类似的东西。您假设的泛型函数除了对其地址(而不是其大小)进行任何操作都不能对其执行任何操作。

If you did have a reference to void, what would you do with it? It wouldn't be a number, or a character, or a pointer, or anything like that. Your hypothetical generic function couldn't perform any operation on it, except taking its address (and not its size).

void有两个用途:放弃任何知识类型(如void *),并且不指定任何内容(与void函数返回相反)。在这两种情况下,都不可能说出一个关于虚空的东西,只是它可能有一个地址。

"void" has two uses: to disclaim any knowledge of type (as in void *), and to specify nothing as opposed to something (void function return). In neither case is it possible to say anything about a void something except that it may have an address.

如果您想不出一种有用的方法,而且我不能,那至少是证明某事无用的证据,而这很可能至少是这里理由的一部分。

If you can't think of a way something can be useful, and I can't, that is at least evidence that something is useless, and that may well be at least part of the rationale here.

这篇关于为什么不可能有无效参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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