大佬教程收集整理的这篇文章主要介绍了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) {}
但是对于clang 3.3版(2545b1d99942080BAC4a74cda92c620123d0d6e9)(2ff97832e593926ea8dbdd5fc5bcf3@R_801_11287@75638a9)
它给出了这个错误:
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.
哪一个是对的?
首先要注意的是,没有非好友代码应该能够正确地报告给定私有成员的存在.因此,如果您尝试这样做,则必须修改您的设计.一个类可以对其私有成员执行任何操作,而其他代码(除了朋友)应该无法知道它.这是设计的.
但是,有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语义,我不打算提交关于此的报告.
以上是大佬教程为你收集整理的c – 使用元编程的私有成员存在测试,GCC vs clang,这是对的吗?全部内容,希望文章能够帮你解决c – 使用元编程的私有成员存在测试,GCC vs clang,这是对的吗?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。