簡體   English   中英

函數調用表達式的類型是什么?

[英]What's the type of the function call expression?

這是一個語言律師問題。 C ++ 11中的第5p5條規定:

如果表達式最初具有“對T的引用”類型(8.3.2,8.5.3),則在進行任何進一步分析之前將類型調整為T. 表達式指定由引用表示的對象或函數,表達式是左值或x值,具體取決於表達式。

另一方面,§5.2.2p3規定:

如果postfix-expression指定析構函數(12.4),則函數調用表達式的類型為void; 否則,函數調用表達式的類型是靜態選擇函數的返回類型(即,忽略虛擬關鍵字),即使實際調用的函數的類型不同。 此類型應為對象類型,引用類型或類型void。

考慮一下這段代碼:

int& f();
f();  // What is the type of this expression?

DR 1261中標准發布后,這已得到糾正。 草案n3485內容如下:

[...]否則,函數調用表達式的類型是靜態選擇函數的返回類型(即,忽略virtual關鍵字),即使實際調用的函數的類型不同。 返回類型應為對象類型,引用類型或cv void

(我的重點;不在你的引言中)。

這兩段現在兼容; 函數調用表達式的(初始)類型現在是int & ,它立即調整為int和value-category lvalue。 返回一個限定類型的函數會發生類似的過程,這樣做的好處是我們不需要擔心左值到參考的轉換:

const int g();
static_assert(std::is_same<decltype(g()), int>::value, "!!!");

f()的類型是int ; 它的價值類別是左值。 你可以證明這個事實:

int& f();
static_assert(std::is_same<int&,decltype((f()))>::value,"EXPLODE");

每個C ++11§7.1.6.2[dcl.type.simple] / 4“......如果e是左值,則decltype(e)T& ,其中Te的類型。

示例代碼:

int& foo() { static int x; return x; }
int bar() { return 0; }

template< class Type >
struct Is_ref_ { static const bool yes = false; };

template< class Type >
struct Is_ref_<Type&> { static const bool yes = true; };

#include <iostream>
using namespace std;
auto main() -> int
{
    cout << boolalpha;
    cout << "Function calls foo versus bar:" << endl;
    cout << Is_ref_<decltype(foo())>::yes << endl;
    cout << Is_ref_<decltype(bar())>::yes << endl;

    int a;
    int& b = a;
    cout << endl;
    cout << "lvalue versus ref:" << endl;
    cout << Is_ref_<decltype(a)>::yes << endl;
    cout << Is_ref_<decltype(b)>::yes << endl;
}

使用Visual C ++ 12.0和MinGW g ++ 4.7.2輸出:

函數調用foo與bar:
真正

左值與參考值:

真正

暫無
暫無

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

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