Top-level const doesn't influence a function signature

后端 未结 7 2023
悲哀的现实
悲哀的现实 2020-11-27 08:32

From the C++ Primer 5th Edition, it says:

int f(int){ /* can write to parameter */}
int f(const int){ /* cannot write to parameter */}

The

7条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 08:48

    In "The C++ Programming Language", fourth edition, Bjarne Stroustrup writes (§12.1.3):

    Unfortunately, to preserve C compatibility, a const is ignored at the highest level of an argument type. For example, this is two declarations of the same function:

    void f(int);
    void f(const int);
    

    So, it seems that, contrarily to some of the other answers, this rule of C++ was not chosen because of the indistinguishability of the two functions, or other similar rationales, but instead as a less-than-optimal solution, for the sake of compatibility.

    Indeed, in the D programming language, it is possible to have those two overloads. Yet, contrarily to what other answers to this question might suggest, the non-const overload is preferred if the function is called with a literal:

    void f(int);
    void f(const int);
    
    f(42); // calls void f(int);
    

    Of course, you should provide equivalent semantics for your overloads, but that is not specific to this overloading scenario, with nearly indistinguishable overloading functions.

提交回复
热议问题