我想知道如果我们有一个函数参数是引用到一个const
函数会发生什么,就像下面所示。
版本 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;
}
版本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;
}
我的问题如下:
- 在函数
func
中的函数参数someFunction
方面,版本1和版本2是否完全相同?即为函数参数someFunction
添加const
不起任何作用(即被简单忽略)。 - 如果在这些示例中忽略了
const
,那么C++标准在什么时候(文档)规定了const
将被忽略。
PS:查看生成的汇编代码似乎可以发现对于函数参数的引用const
被忽略。