c – 使用元编程的私有成员存在测试,GCC vs clang,这是对的吗?
这更像是一个标准问题.
请考虑以下代码: template <typename T> class has_Data { typedef char one; typedef long two; template <typename C> static one test( typeof(&C::Data) ) ; template <typename C> static two test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; }; class MyClass { private: struct Data { }; }; void function(bool val = has_Data<MyClass>::value) {} 上面的代码适用于gcc(GCC)4.4.3 但是对于clang 3.3版(2545b1d99942080bac4a74cda92c620123d0d6e9)(2ff97832e593926ea8dbdd5fc5bcf367475638a9) 它给出了这个错误: test_private_data.cpp:7:54: error: 'Data' is a private member of 'MyClass' template <typename C> static one test( typeof(&C::Data) ) ; ^ /devshared/home/rhanda/test_private_data.cpp:7:37: note: while substituting explicitly-specified template arguments into function template 'test' template <typename C> static one test( typeof(&C::Data) ) ; ^ /devshared/home/rhanda/test_private_data.cpp:21:26: note: in instantiation of template class 'has_Data<MyClass>' requested here void function(bool val = has_Data<MyClass>::value) {} ^ 1 error generated. 哪一个是对的? 从标准文件(n3485),我发现一个声明似乎比gcc更赞同clang.
解决方法
我认为海湾合作委员会是对的.
首先要注意的是,没有非好友代码应该能够正确地报告给定私有成员的存在.因此,如果您尝试这样做,则必须修改您的设计.一个类可以对其私有成员执行任何操作,而其他代码(除了朋友)应该无法知道它.这是设计的. 但是,有SFINAE原则:替换失败不是错误.由于MyClass :: Data是私有的,所以has_Data中的代码应该 – 在我看来 – 就好像根本没有C :: Data成员一样.因此,第一个函数会导致替换失败,它会被忽略,第二个函数就是使用的函数.添加更多代码,我的GCC 4.7.2编译没有问题,并且has_Data< MyClass> :: value评估为false.在我看来,纠正SFINAE. 我试图用the document you referred to的引文来支持这个观点,我在第14.8.2节第8段中找到了以下内容:
这是标准中的非规范性注释,但对我来说似乎是一个非常可读和清晰的指示,SFINAE实际上应该适用于这种情况,就像GCC处理它一样. 编辑:正如a comment在a comment中所指出的,上述仅适用于C 11.在旧版本的标准中,情况曾经不同. Issue 1170: Access checking during template argument deduction详细说明了这一变化. 由于typeof是GNU扩展,GCC不会使用-std = c 03或-std = c 11编译此代码. -std = gnu 03仍然可以编译代码的事实可能被认为是不合适的,但由于前进的方式是使用C 11语义,我不打算提交关于此的报告. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |