Effective C++ Item 47 通过traits classes获取类型信息
#include <iostream>
#include <typeinfo>
// 定义traits template
template<typename T>
struct TypeTraits {
// 默认实现
typedef T BasicType;
static const bool isPointer = false;
static const bool isReference = false;
};
// 为指针类型特化traits template
template<typename T>
struct TypeTraits<T*> {
typedef T BasicType;
static const bool isPointer = true;
static const bool isReference = false;
};
// 为引用类型特化traits template
template<typename T>
struct TypeTraits<T&> {
typedef T BasicType;
static const bool isPointer = false;
static const bool isReference = true;
};
int main() {
int a = 0;
int* ptr = &a;
int& ref = a;
std::cout << "Type of a is " << typeid(a).name() << std::endl;
std::cout << "isPointer: " << TypeTraits<decltype(a)>::isPointer << std::endl;
std::cout << "isReference: " << TypeTraits<decltype(a)>::isReference << std::endl;
std::cout << "Type of ptr is " << typeid(ptr).name() << std::endl;
std::cout << "isPointer: " << TypeTraits<decltype(ptr)>::isPointer << std::endl;
std::cout << "isReference: " << TypeTraits<decltype(ptr)>::isReference << std::endl;
std::cout << "Type of ref is " << typeid(ref).name() << std::endl;
std::cout << "isPointer: " << TypeTraits<decltype(ref)>::isPointer << std::endl;
std::cout << "isReference: " << TypeTraits<decltype(ref)>::isReference << std::endl;
return 0;
}
这段代码定义了一个traits template TypeTraits
,并为指针类型和引用类型分别进行了特化。在main函数中,我们使用decltype
来获取变量的类型,并使用traits template来获取关于该类型的额外信息,如是否为指针或引用。这个例子展示了traits classes在C++编程中的应用,它们可以用来获取类型信息,进而编写与类型无关的通用代码。
评论已关闭