Overloading on const and volatile- why does it work by reference?

后端 未结 2 768
迷失自我
迷失自我 2020-12-19 11:23

I have the code:

#include \"stdafx.h\"
#include 

using namespace std;


void func(const int& a)
{
    std::cout << \"func(const)\"         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-19 12:00

    The issue is that the top level const and/or volatile are ignored in overload resolution. So

    void foo(const int);
    

    is exactly the same as

    void foo(int);
    

    and similarly for volatile. This is a language rule, and it makes sense since the arguments are passed by value. On the other hand, reference to const/volatile or pointer to const/volatile have a different meaning: you are not allowed to call non-const/volatile methods on what they refer to or point to. Here, the const volatile are not top level.

    void foo(int& i);       // can modify what i refers to, and this has effects outside of foo.
    void foo(const int& i); // cannot modify what i refers to
    

    The two above declarations have very different semantics, so the language makes them distinct concerning overload resolution.

提交回复
热议问题