簡體   English   中英

使用聲明和 function 默認 arguments

[英]The using declaration and function default arguments

根據 C++ 17 標准(10.3.3 使用聲明)

1 using-declaration98 中的每個 using-declarator 都將一組聲明引入到 using-declaration 出現的聲明性區域中。

10 using-declaration 是一種聲明,因此可以在允許(且僅在)允許多個聲明的情況下重復使用。

和(C++ 17 標准,11.3.6 默認參數)

  1. ...當通過使用聲明 (10.3.3) 引入 function 的聲明時,與聲明相關的任何默認參數信息也會被告知。 If the function is redeclared thereafter in the namespace with additional default arguments, the additional arguments are also known at any point following the redeclaration where the using-declaration is in scope.

所以這個程序

#include <iostream>

void f( int x, int y = 20 )
{
    std::cout << "x = " << x << ", y = " << y << '\n';
}

int main() 
{
    using ::f;
    void f( int, int );
    
    f( 10 );
    
    return 0;
}

正如預期的那樣編譯和輸出

x = 10, y = 20

實際上它類似於程序

#include <iostream>

void f( int x, int y )
{
    std::cout << "x = " << x << ", y = " << y << '\n';
}

int main() 
{
    void f( int, int = 20 );
    void f( int, int );
    
    f( 10 );
    
    return 0;
}

現在,以下程序也是有效的,這在邏輯上是一致的。

#include <iostream>

void f( int x, int y = 20 )
{
    std::cout << "x = " << x << ", y = " << y << '\n';
}

int main() 
{
    using ::f;
    
    void f( int, int );

    f( 10 );
    
    void f( int = 10, int );
    
    f();
    
    return 0;
}

但是,該程序無法編譯。

另一方面,考慮以下程序。

#include <iostream>

namespace N
{
    int a = 10;
    int b = 20;
    
    void f( int, int = b );
}

int a = 30;
int b = 40;

void N::f( int x = a, int y )
{
    std::cout << "x = " << x << ", y = " << y << '\n';
}

int main() 
{
    using N::f;
    
    f();
    
    return 0;
}

編譯成功,其 output 為

x = 10, y = 20

那么,同樣的原則是否可以應用於 using 聲明引入的函數?

不允許這樣添加默認 arguments 的原因是什么?

您只能在與原始聲明相同的 scope 中聲明新的默認 arguments。 using不會改變這一點。

對於非模板函數,可以在同一 scope 中的 function 的后續聲明中添加默認 arguments。

dcl.fct.default/4

我相信

與聲明相關的任何默認參數信息也會被告知

並不意味着arguments實際上被導入到scope中,只是知道它們確實存在並且可以使用。

這意味着void f( int = 10, int ); 沒有添加到void f( int x, int y = 20 ) ,而是嘗試添加到void f( int, int ); 這將是非法的,因為使用聲明所在的 scope 中的第二個參數沒有默認參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM