我应该在C ++中什么时候使用typedef? [英] When should I use typedef in C++?

查看:657
本文介绍了我应该在C ++中什么时候使用typedef?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C ++(MFC)编程中,我从来没有觉得需要使用 typedef ,所以我真的不知道它是什么用的。我应该在哪里使用它?是否有任何真实的情况下,使用 typedef 是首选?

解决方案

模板元编程



许多模板元编程中的

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 
$ b

In 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) {
    ...
}

这篇关于我应该在C ++中什么时候使用typedef?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆