I want to know what happens if we have a function parameter that is a reference to a const
function as shown below.
Version 1
int anotherFunc()
{
std::cout<<"inside anotherFunc"<<std::endl;
return 5;
}
void func(decltype(anotherFunc) const &someFunction)//note the const here
{
std::cout<<"inside func"<<std::endl;
std::cout<<someFunction()<<std::endl;
}
int main()
{
std::cout << "Hello World" << std::endl;
func(anotherFunc);
return 0;
}
Version 2
int anotherFunc()
{
std::cout<<"inside anotherFunc"<<std::endl;
return 5;
}
void func(decltype(anotherFunc) &someFunction)//note the missing const here
{
std::cout<<"inside func"<<std::endl;
std::cout<<someFunction()<<std::endl;
}
int main()
{
std::cout << "Hello World" << std::endl;
func(anotherFunc);
return 0;
}
My questions are:
- Are version 1 and version 2 completely equivalent in terms of the function parameter
someFunction
of the functionfunc
? That is addingconst
for the function paramtersomeFunction
does nothing(i.e.,simply ignored). - If
const
is ignored in these examples then at what point(document) does the C standard specify thatconst
will be ignored for this case.
PS: Looking at the generated assembly it does seem that const
is ignored for reference to function parameter.
CodePudding user response:
Yes, the const
qualifier is ignored when added to an alias for a function type.
From the standard, [dcl.fct]/7:
The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored.
[Note 4: A function type that has a cv-qualifier-seq is not a cv-qualified type; there are no cv-qualified function types. — end note]
[Example 4:
typedef void F(); struct S { const F f; // OK: equivalent to: void f(); };
— end example]
CodePudding user response:
- Are version 1 and version 2 completely equivalent in terms of the function parameter someFunction of the function func?
Yes. There is no such thing as const qualified function type, and as such no thing as reference to const function. If you were to apply const to explicitly written reference to function type, then the program would be ill-formed. But when the const is applied to a type alias or type deduction, then the const is ignored.
- does the C standard specify that const will be ignored for this case.
Yes.