Can reserved function names be overloaded?

2019-04-06 14:37发布

问题:

This question is a follow-up question of this one.

Consider the following program:

#include <cmath>

// meaningless, only for language-lawyer purpose
void abs(void*) {}

int main(){
    abs(nullptr);
}

Does this program result in undefined behavior?


The related part in the standard is [extern.names]/4:

Each function signature from the C standard library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage, or as a name of namespace scope in the global namespace.

I'm not sure whether overloading is permitted.

回答1:

There are two parts to this statement, as it talks about names (from the C standard) that are reserved (for C++ implementations). In particular,

Part 1: Each function signature from the C standard library declared with external linkage

This includes the C library function abs

Part 2: is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage, or as a name of namespace scope in the global namespace.

So the name ::abs is reserved for the C++ implementation. You can't use it. Overloading is irrelevant.



回答2:

tl;dr - yes, you can

http://www.eel.is/c++draft/reserved.names#extern.names

Pulling in the rest of the context:

20.5.4.3.2: If a program declares or defines a name in a context where it is reserved, other than as explicitly allowed by this Clause, its behavior is undefined.

And then also

20.5.4.3.3.2 Each global function signature declared with external linkage in a header is reserved to the implementation to designate that function signature with external linkage.

20.5.4.3.3.4 Each function signature from the C standard library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage,182 or as a name of namespace scope in the global namespace.

These suggest you can, as it is only the signature that is reserved.

Bonus for namespace ::std

http://www.eel.is/c++draft/library#namespace.std

20.5.4.2.1.1 Unless otherwise specified, the behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std.

http://en.cppreference.com/w/cpp/language/extending_std has summarised the exceptions