Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of 14.8.2 paragraphs 3 and 4 in the C++ Standard?

I'm struggling to understand this rule, specially the sentences in bold below (my emphasis):

Consider the comment #2 in the snippet below: what does it mean to say that the function type is f(int), but t is const?

§14.8.2/3:

After this substitution is performed, the function parameter type adjustments described in 8.3.5 are performed. [ Example: A parameter type of “void ()(const int, int[5])” becomes “void(*)(int,int*)”. —end example ] [ Note: A top-level qualifier in a function parameter declaration does not affect the function type but still affects the type of the function parameter variable within the function. —end note ] [ Example:

template <class T> void f(T t);
template <class X> void g(const X x);
template <class Z> void h(Z, Z*);
int main() {
    // #1: function type is f(int), t is non const
    f<int>(1);
    // #2: function type is f(int), t is const
    f<const int>(1);
    // #3: function type is g(int), x is const
    g<int>(1);
    // #4: function type is g(int), x is const
    g<const int>(1);
    // #5: function type is h(int, const int*)
    h<const int>(1,0);

}

—end example ]

§14.8.2/4:

[ Note: f<int>(1) and f<const int>(1) call distinct functions even though both of the functions called have the same function type. —end note ]

like image 904
Mao Avatar asked Jul 07 '14 18:07

Mao


2 Answers

Consider:

template <class T> void f(T t) { t = 5; }

f<int> is well-formed, but f<const int> is not, because it attempts to assign to a const variable.

See: Use of 'const' for function parameters

like image 132
ecatmur Avatar answered Oct 23 '22 20:10

ecatmur


If you had two functions

void f(int x);
void g(const int x);

then both functions would have the same function type. This type is denoted void(int), and a function pointer of type void (*)(int) would be able to point to either function.

This is what is meant when we say that the top-level const-qualifiers on the parameters to a function do not affect the type of the function.

However, this does not mean that the const is meaningless. In the definition of f, you would be able to modify x, but in the definition of g, you would not be able to modify x, since x has type const int.

like image 26
Brian Bi Avatar answered Oct 23 '22 19:10

Brian Bi