gpt4 book ai didi

c++ - C++ 中对 const Callable 的引用和对 Callable 的引用之间的区别

转载 作者:行者123 更新时间:2023-12-04 12:17:52 30 4
gpt4 key购买 nike

我想知道如果我们有一个引用 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 和版本 2 在函数参数 someFunction 方面完全等效吗?功能func ?即添加 const对于函数参数 someFunction什么都不做(即,简单地被忽略)。
  • const在这些示例中被忽略,那么 C++ 标准在什么时候(文档)指定 const在这种情况下将被忽略。

  • PS:查看生成的程序集,似乎 const被忽略以引用函数参数。

    最佳答案

    是的,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]

    关于c++ - C++ 中对 const Callable 的引用和对 Callable 的引用之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69218804/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com