更新时间:2022-11-23 11:52:36
typedef
是必需的
typedef
作为编译时类型值生成的类型。例如。考虑一个简单的元函数,用于将指针类型转换为其基本类型: template< typename T&
struct strip_pointer_from;
template< typename T>
struct strip_pointer_from< T *> {//指针类型的部分专门化
typedef T type;
};
示例: strip_pointer_from< double *> :: type
计算为 double
。注意,模板元编程在库开发之外不常用。
typedef
是一种有用的,可以为复杂的函数指针类型提供一个简短的别名:
typedef int(* my_callback_function_type)(int,double,std :: string); bb
$ bIn my years of C++ (MFC) programming in I never felt the need to use typedef
, so I don't really know what is it used for. Where should I use it? Are there any real situations where the use of typedef
is preferred? Or is this really more a C-specific keyword?
Template Metaprogramming
typedef
is necessary for many template metaprogramming tasks -- whenever a class is treated as a "compile-time type function", a typedef
is used as a "compile-time type value" to obtain the resulting type. E.g. consider a simple metafunction for converting a pointer type to its base type:
template<typename T>
struct strip_pointer_from;
template<typename T>
struct strip_pointer_from<T*> { // Partial specialisation for pointer types
typedef T type;
};
Example: the type expression strip_pointer_from<double*>::type
evaluates to double
. Note that template metaprogramming is not commonly used outside of library development.
Simplifying Function Pointer Types
typedef
is helpful for giving a short, sharp alias to complicated function pointer types:
typedef int (*my_callback_function_type)(int, double, std::string);
void RegisterCallback(my_callback_function_type fn) {
...
}