簡體   English   中英

這是否使用函數類型(非指針)的別名與此typedef相同

[英]Is this using alias for a function type (not pointer) the same as this typedef

這些都一樣嗎?

using on_receipt = void (const string);

typedef void on_receipt(const string);

這些不是函數指針的別名,而是實際的函數類型。 他們都編譯得很好。 奇怪的是, typedef版本至少有函數名稱的占位符,但由於using=之前移動了這個占位符,因此返回和參數之間沒有任何區別,看起來它可能是錯誤的或誤導性的。

對,他們是:

[dcl.typedef]

2別名聲明也可以引入typedef-name。 using關鍵字后面的標識符變為typedef-name,並且該標識符后面的可選attribute-specifier-seq屬於該typedef-name。 它具有與typedef說明符引入的語義相同的語義。 特別是,它沒有定義新類型。

實例

#include <string>
#include <type_traits>

int main()
{
    using on_receipt1 = void (const std::string);    
    typedef void on_receipt2(const std::string);
    static_assert(std::is_same<on_receipt1, on_receipt2>::value, "");
}

你想錯了。 on_receipt不是“函數名稱的占位符”,它是您引入的類型名稱。 考慮一下使用情況。

你會像on_receipt function_variable;一樣使用它on_receipt function_variable; ,所以你的解釋實際上是誤導性的,因為你引用你的函數的“名稱”不是on_receipt而是function_variable

我會說函數的typedef語法相當奇怪。 using樣式時,您在一側具有類型名稱,而在另一側具有定義它的事物。 typedef樣式中,您將它交錯。

typedef有點看起來像一個函數聲明,但它確實不是; 這是一種類型聲明。 我覺得很亂。

哦,當然,這些陳述是等價的。

暫無
暫無

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

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