标签:object type technique C++ traits template pointer
C++ Traits是什么?
Think of a trait as a small object whose main purpose is to carry information used by another object or algorithm to determine "policy" or "implementation details". - Bjarne Stroustrup
Trait 将类型的性质、特性封装起来,可用于判断类型的特性:
- 这个类型是否为 pointer ?
- 这个类型是否为 reference ?
- 这个类型是否具体某个特性?
在实现通用的算法或业务逻辑时,可以根据数据类型的特性,选择不同的实现细节
实例1:is_pointer
template <typename T> struct is_pointer { static const bool value = false; }; template <typename T> struct is_pointer<T*> { static const bool value = true; }; template<typename T> void algorithm(T& object) { std::cout << "is_pointer:" << is_pointer<T>::value << std::endl; } int main() { int a = 100; algorithm(a); int *b = &a; algorithm(b); return 0; }
参考资料
An introduction to C++ Traits
https://accu.org/index.php/journals/442
C++ Reference: type_traits
http://www.cplusplus.com/reference/type_traits/
标签:object,type,technique,C++,traits,template,pointer 来源: https://www.cnblogs.com/benxie/p/11356863.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。