4
在C++中使類模板的基類規範B
依賴於類的私有定義A
它與類模板B
的朋友是否合法?示例代碼:訪問朋友類模板的基本子句中的私人定義
struct Empty {};
template <typename T>
struct B;
struct A
{
friend struct B<A>;
private:
using Base = Empty;
};
template <typename T>
struct B : T::Base
{
};
int main()
{
B<A> test;
return 0;
}
Godbolt鏈接:https://godbolt.org/g/HFKaTQ
代碼編譯罰款鏘幹線(及以上版本)和MSVC 19(VS 2017),但未能與GCC主幹(及以上版本)編譯:
test.cpp: In instantiation of 'class B<A>':
test.cpp:21:7: required from here
test.cpp:15:8: error: 'using Base = class Empty' is private within this context
struct B : T::Base
^
test.cpp:11:20: note: declared private here
using Base = Empty;
^
哪個編譯器錯了?
編輯:順便說一句,如果B
轉換爲常規類(刪除模板參數)代碼編譯GCC中。所以,我想它也應該在類模板的情況下工作。另外cppreference說:「朋友本身也可以繼承這個類的私有和受保護的成員(自C++ 11以來)」
針對GCC提交[拒絕有效]錯誤報告。他們很可能會承認這是一個錯誤,但也許他們會告訴你爲什麼他們認爲它不合格。 – Brian
@Brian是的,謝謝。我已經在過去幾周做過這個,但忘記了更新問題/提供答案。 – w1th0utnam3