我想知道,如果我們有一個函式引數是對const函式的參考,會發生什么,如下所示。
版本1
int anotherFunc()
{
std::cout<<"internat anotherFunc"<<std::endl。
return 5;
}
void func(decltype(otherFunc) const & someFunction)//注意這里的const。
{
std::cout<<"inside func"<<std::endl。
std::cout<<someFunction()<<std::endl。
}
int main()
{
std::cout << "Hello World" << std::endl。
func(otherFunc)。
return 0。
第2版
int anotherFunc()
{
std::cout<<"internat anotherFunc"<<std::endl。
return 5;
}
void func(decltype(otherFunc)& someFunction)//注意這里缺少const。
{
std::cout<<"inside func"<<std::endl。
std::cout<<someFunction()<<std::endl。
}
int main()
{
std::cout << "Hello World" << std::endl。
func(otherFunc)。
return 0。
我的問題是:
- 在函式
func的函式引數someFunction方面,版本1和版本2是否完全等同?也就是說,為函式引數someFunction添加const沒有任何作用(即,簡單地忽略了)。 - 如果
const在這些例子中被忽略,那么C 標準在哪一點(檔案)規定const在這種情況下將被忽略。
PS: 看一下生成的程式集,似乎const對于函式引數的參考是被忽略的。
uj5u.com熱心網友回復:
是的,const修飾符在添加到函式型別的別名時被忽略了。
從標準中,[dcl.fct]/7:
函式宣告器中的cv-qualifier-seq的效果與在函式型別之上添加cv-qualification的效果不一樣。在后一種情況下,cv-qualifiers被忽略了。 [注4:具有cv-qualifier-seq的函式型別不是cv-qualified型別;不存在cv-qualified函式型別。- 結束語]
[例4:typedef void F()。 結構 S { const F f; // OK: equivalent to: void f(); };-結束示例]
uj5u.com熱心網友回復:
- 在函式func的函式引數someFunction方面,版本1和版本2是否完全等同?
是的,不存在所謂的const限定的函式型別,因此也不存在對const函式的參考。如果你將 const 應用于明確寫出的對函式型別的參考,那么程式將是不符合格式的。但是當const被應用于一個型別別名或型別演繹時,那么const就會被忽略。
- 在這種情況下,C 標準是否規定const將被忽略。
是的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/326660.html
標籤:
上一篇:從字典串列中洗掉單個值
