C++: C++ type traits technique
作者:互联网
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