jeudi 16 septembre 2021

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.

Aucun commentaire:

Enregistrer un commentaire