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:
someFunction
of the function func
? That is adding const
for the function paramter someFunction
does nothing(i.e. simply ignored).const
is ignored in these examples then at what point(document) does the C++ standard specify that const
will be ignored for this case.PS: Looking at the generated assembly it does seem that const
is ignored for reference to function parameter.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With