c 11 – 是否非法獲取“sizeof”非靜態成員巢狀在類模板中?
在clang / llvm 3.6.2中,使用std = c編譯時,以下程式碼會導致編譯錯誤11:
template <typename T=void> class bar { public: struct foo { int array[10]; }; int baz() { return sizeof(foo::array); } }; int main(void) { bar<> b; return b.baz(); }
命令列呼叫:
$clang++ -std=c++11 nonstatic.cpp -o nonstatic nonstatic.cpp:12:28: error: invalid use of non-static data member 'array' return sizeof(foo::array); ~~~~~^~~~~ nonstatic.cpp:20:14: note: in instantiation of member function 'bar<void>::baz' requested here return b.baz();
如果我更改吧,不再是一個模板,如同
class bar { public: struct foo { int array[10]; }; int baz() { return sizeof(foo::array); } }; int main(void) { bar b; return b.baz(); }
那麼程式碼乾淨地編譯.值得注意的是,GCC 5.2.1接受std = c 11下的兩個版本.另外值得注意的是,將陣列移動到封閉的類模板體中(但將其作為模板)也導致cl ang接受.
哪個行為對標準是正確的?這是GCC,cl,還是兩者都有錯?
(我在cfe使用者上問了ofollow,noindex" target="_blank">question ,但到目前為止還沒有收到回覆).
這當然是cl蟲您的sizeof表示式的運算元是表示非靜態資料成員的id表示式,因此[expr.prim.general] / 13成立.這是一個簡單的例子:
template<class T> struct M { int f() { return sizeof(T::x); } }; struct S { int x; }; int main() { return M<S>{}.f(); }
當在模板例項方法中的未經評估的上下文中訪問依賴型別成員時,該錯誤將展現出來. Clang執行n2253 rule enabling the use of non-static data members in unevaluated context (及以後的改進)似乎相當脆弱,並與模板互動不好;一個類似(雖然不同)的bug是http://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20151019/141535.html .
我沒有找到任何跡象表明這已經報告到Clang Bugzilla ;你可能想要開啟一個新的錯誤.
根據您的情況,解決方法可能包括在例項方法之外移動靜態型別和值計算;特別是甚至使baz的靜態成員函式足以說服cl to接受你的程式碼.
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/35901577/is-it-illegal-get-sizeof-non-static-member-of-struct-nested-within-class-templ