簡體   English   中英

為什么我不能通過模板參數聲明一種友元函數,但可以使用別名

[英]Why can't I declare a type of friend function by template parameter but can with alias

考慮一下代碼:

template <class T>
class Bar {
    int foobar;
    using X = T();
    friend X foo;
};

void foo() {
    Bar<void> bar;
    bar.foobar = 1;
    static_cast<void>(bar);
}

int main() {}

gccclang中編譯都很好。 但看似相同的代碼:

template <class T>
class Bar {
    int foobar;
    friend T foo;
};

void foo() {
    Bar<void()> bar;
    bar.foobar = 1;
    static_cast<void>(bar);
}

int main() {}

導致gccclang都出錯。 為什么模板參數在這里與別名等效?

因為T foo被解析為對象的聲明,並且模板的實例化不能將對象的聲明更改為函數的聲明。

C ++標准/ [temp.spec]:

如果函數聲明通過依賴類型(17.7.2.1)獲取其函數類型而不使用函數聲明符的語法形式,則該程序格式錯誤。

暫無
暫無

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

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