C++ 模板的又一特征

皮贝贝 posted @ 2009年12月24日 20:12 in 模板元编程 with tags template c++ , 1679 阅读

众所周知, C++ 的模板元编程中,  元数据即 常量 和 类型, 很多时候我们可以通过函数重载机制来解决一些问题, 而且编译器在对模板的成员函数的编译上会采取偷懒战术. 但是, 编译器还有另一个偷懒战术, 那就是在函数的参数上:

这个问题源于我在 csdn 上的一个讨论: 如何得知一个类型是否可以进行 [ ] 下标运算. 然后有人出了答案, 答案中有这样一句:

 

template<typename T, typename U>
struct Dummy;

template<typename T, typename U>
Has_Op op_checker( const Dummy<T,&T::operator[]>* const );

 

 

 

问题就出在这里了,  求 [ ] 运算符的类型,用 &T::operator[ ] 是无法编译通过的. 所以, 我采取了迂回战术, 绕过了这个类型问题, 采用另一种元数据: 常量来解决的:

 

template<typename T, size_t N>
struct Dummy;

template<typename T, typename U>
Has_Op op_checker( const Dummy<T,sizeof(&T::operator[])>* const );

 

 

 

这样就能编译通过(gcc)了, 而且似乎是正确的.

此时, 编译器在编译时, 会试图对 op_checker 的"特化"版本( 函数重载的特化 ) 进行匹配, 要匹配就要查找 operator [ ], 若找到, 就用这个特化版本. 否则查找其他的.

所以说, 在参数的处理上, 这种现象也可以作为模板的一种工具来进行使用.

 

  • 无匹配
Avatar_small
Kerala 2nd Class Bo 说:
2023年9月25日 16:07

Kerala 2nd Standard Malayalam, English, Tamil, and Kannada Medium Textbook Available in SCERT Kerala Official Website, Students can Download Latest Edition, SCERT Kerala Standard Books are Prepared by a Group of Subject Expert, These SCERT Kerala Textbooks 2024 are an Excellent Resource for Students, as they can learn and revise through Different Chapters Present in the syllabus for Kerala 2nd Class Book 2024 Subjects like Maths, Science, Social Science, Hindi, English and Malayalam.This is Kerala Textbook.

Avatar_small
boardmodelpaper.com 说:
2024年1月23日 14:52

Board Model Papers 2024 Download with Suggestions for 10th Class Textbooks 2024 Pdf Download and SSLC New Syllabus Sample Question Paper 2024 and different types of model papers boardmodelpaper.com and question papers for following the website and Arts, Science, Commerce Stream Subject Wise Solved Question Bank for Hindi & English Medium Students with Exam Pattern & Blueprint and subject Wise with 11th & 12th Question Bank 2024 for General & Vocational Course Languages & Subjects Important Question for the above link.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter