Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Reference to a const Callable and Reference to a Callable in C++

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:

  1. Are version 1 and version 2 completely equivalent in terms of the function parameter someFunction of the function func? That is adding const for the function paramter someFunction does nothing(i.e. simply ignored).
  2. If 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.

like image 454
Anoop Rana Avatar asked Sep 17 '21 06:09

Anoop Rana


Video Answer


1 Answers

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]

like image 108
songyuanyao Avatar answered Sep 22 '22 06:09

songyuanyao