Why are argument modifiers (ie, "Const" or "volatile") not considered part of a function or signature type?

Please note that the following two functions are of the same type and signature:

void foo1(int t) {} // foo1 has type 'void(*)(int)', and signature '(*)(int)' void foo2(const int t) {} // Also type 'void(*)(int)', signature '(*)(int)' 

( const not part of a function type or function signature). Similarly, a modifier ( const or volatile ) on the type of the return value does not affect the type of the function or the signature of the function.

However, in the function definition itself (not shown), the named variable t supports the const qualification in foo2 .

There are many StackOverflow questions discussing why the return type of a function is not considered as part of the function signature (used to allow overloading).

However, I cannot find a StackOverflow question that asks why argument modifiers ( const or volatile ) are not part of a function type or signature. Also, I looked right in the C ++ 11 standards document and it's hard to figure out.

What is the rationale for the fact that argument modifiers (i.e., const and volatile ) are not part of a function or signature type?

ADD . For clarity, from R.MartinhoFernandes below, I should clarify that in C ++ (I think) the modifiers of the const and volatile arguments are ignored only as part of the type of the / signature function if they are top-level modifiers - see this answer below.

+6
source share
1 answer

What is the rationale for the fact that argument modifiers (i.e., const and volatile) are not part of a function or signature type?

From the perspective of the caller, there is no difference between void foo(int) and void foo(int const) . No matter what you pass, it will not be changed, regardless of the modifier: the function will receive a copy.

From the developer's point of view, the only difference is that with void foo(int x) you can mutate x (i.e. your local copy) in the body, but you cannot mutate x with void foo(int const x) .

C ++ confirms these two points of view. The caller's perspective is confirmed by the fact that the two declarations are void foo(int); and void foo(int const); declare the same function. The implementation perspective is confirmed by the fact that you can declare a function as void foo(int x); , but define it as void foo(int const x) { /*...*/ } if you want you to not accidentally assign an argument.

Note that this only applies to the upper level const , i.e. const , which applies to the whole type. In things like int const& or int const* , the modifier applies only to a part of the type like a "pointer to (const (int))", so it is not the top level of const . In int *const , however, const again applied to the whole type, as in "const (pointer to (int))".

+11
source

All Articles