Top-level const doesn't influence a function signature

后端 未结 7 2034
悲哀的现实
悲哀的现实 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:56

    Answering this part of your question:

    What I really care is why C++ doesn't allow these two functions simultaneously as different function since they are really different as to "whether parameter can be written or not". Intuitively, it should be!

    If you think about it a little more, it isn't at all intinuitive - in fact, it doesn't make much sense. As everybody else has said, a caller is in no way influenced when a functon takes it's parameter by value and it doesn't care, either.

    Now, let's suppose for a moment that overload resolution worked on top level const, too. Two declarations like this

    int foo(const int);
    int foo(int);
    

    would declare two different functions. One of the problems would be which functions would this expression call: foo(42). The language rules could say that literals are const and that the const "overload" would be called in this case. But that's the least of a problem. A programmer feeling sufficiently evil could write this:

    int foo(const int i) { return i*i; }
    int foo(int i)       { return i*2; }
    

    Now you'd have two overloads that are appear semanticaly equivalent to the caller but do completely different things. Now that would be bad. We'd be able to write interfaces that limit the user by the way they do things, not by what they offer.

提交回复
热议问题