c++referencevoid-pointers

Why is it impossible to have a reference-to-void?


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

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

Why is it that way? Why can't I write a "generic" function that accept a 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.


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
}

Solution

  • 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" 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.