C++中引用到const Callable和引用到Callable的区别

5

我想知道如果我们有一个函数参数是引用到一个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;
}

我的问题如下:

  1. 在函数func中的函数参数someFunction方面,版本1和版本2是否完全相同?即为函数参数someFunction添加const不起任何作用(即被简单忽略)。
  2. 如果在这些示例中忽略了const,那么C++标准在什么时候(文档)规定了const将被忽略。

PS:查看生成的汇编代码似乎可以发现对于函数参数的引用const被忽略。

2个回答

6

是的,当添加到函数类型的别名时,const限定符会被忽略。

根据标准,来自[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]


3
  1. 版本1和版本2在函数func的函数参数someFunction方面完全等效吗?

是的。没有const修饰的函数类型,因此也不存在对const函数的引用。如果您将const应用于显式写入的函数类型引用,则程序将无法执行。但是,当const应用于类型别名或类型推断时,const将被忽略。

  1. C++标准是否指定在这种情况下const将被忽略?

是的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接