[英]Should a friend function of a class template become friend to all instantiations?
考慮以下代碼段:
template<typename T> struct Foo {
friend void bar(Foo, Foo<char> f) {
static_cast<void>(f.private_field); // Should only compile when friends with Foo<char>.
}
private:
int private_field{};
};
int main() {
bar(Foo<char>{}, Foo<char>{}); // Compiles.
bar(Foo<bool>{}, Foo<char>{}); // Compiles erroneously?
}
它可以使用主干(截至 2020 年 5 月 6 日)GCC 成功編譯,但不能使用 Clang 和 MSVC 編譯:請參閱Godbolt 。
誰在這里?
來自 Clang 和 MSVC 的錯誤消息與預期一致:
<source>:3:29: error: 'private_field' is a private member of 'Foo<char>'
static_cast<void>(f.private_field); // Should only compile when friends with Foo<char>.
^
<source>:11:5: note: in instantiation of member function 'bar' requested here
bar(Foo<bool>{}, Foo<char>{}); // Compiles erroneously?
^
<source>:6:9: note: declared private here
int private_field{};
^
1 error generated.
Compiler returned: 1
和
example.cpp
<source>(3): error C2248: 'Foo<char>::private_field': cannot access private member declared in class 'Foo<char>'
<source>(6): note: see declaration of 'Foo<char>::private_field'
<source>(2): note: see declaration of 'Foo<char>'
<source>(2): note: while compiling class template member function 'void bar(Foo<bool>,Foo<char>)'
<source>(11): note: see reference to function template instantiation 'void bar(Foo<bool>,Foo<char>)' being compiled
<source>(11): note: see reference to class template instantiation 'Foo<bool>' being compiled
Compiler returned: 2
GCC 在這里顯然是錯誤的:因為每個專業化定義了自己單獨的朋友 function (必須避免重復定義錯誤), bar(Foo<char>,Foo<char>)
是Foo<char>
<char> 的朋友,但bar(Foo<char>,Foo<char>)
不是。 該標准包含一個相關示例,其中提到了一個非常相似的案例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.