c++ 关键字 typename 和 typedef

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/I_can_do_1098/article/details/53670980

一下英文内容摘自MSDN,中文内容属于bz自己的理解
typename 通常在模板里用到,我们来讲讲它到底是个什么玩意

typename: Tells the compiler that an unknown identifier is a type.

告诉编译器,这个未知的定义是个类型

typename identifier;

Use this keyword only in template definitions.

This keyword must be used if the name is a qualified name dependent on a template argument; it is optional if the qualified name is not dependent. For more information, see Templates and Name Resolution.

定义可变模板参数时必须使用此关键字;

typename can be used by any type anywhere in a template declaration or definition. It is not allowed in the base class list, unless as atemplate argument to a template base class.

example0:
template <class T>
class C1 : typename T::InnerType // Error - typename not allowed.
{};
template <class T>
class C2 : A<typename T::InnerType>  // typename OK.
{};

看了上面这个例子0再结合前面那段话,意思就是它不能直接出现在父类列表里,除非用作模板基础类的模板参数。

The typename keyword can also be used in place of class in template parameter lists. For example, the following statements are identical:

example1:
template<class T1, class T2>...
template<typename T1, typename T2>...

它可以用来代class,说实话这种情况倒是我们比较常见的。

example2:
// typename.cpp
template<class T> class X
{
   typename T::Y m_y;   // treat Y as a type
};

int main()
{
}

看到最后我们明白了,这个东西就是告诉编译器,这个东西你不要管了,它是一个类型。

说完了,typename就要说一下typedef了,为什么要一起说呢?因为它俩长得太像了。

typedef: type-declaration synonym

A typedef declaration introduces a name that, within its scope, becomes a synonym for the type given by the type-declaration portion of the declaration.

You can use typedef declarations to construct shorter or more meaningful names for types already defined by the language or for types that you have declared. Typedef names allow you to encapsulate implementation details that may change.

In contrast to the class, struct, union, and enum declarations, typedef declarations do not introduce new types — they introduce new names for existing types.

Typedef names share the name space with ordinary identifiers.Therefore, a program can have a typedef name and a local-scope identifier by the same name.

扯的挺高端,说白了就是宏定义,原理一样的文本替换而已,作为一个实用主义者,首先搞明白它应该怎么用。

1.指定一个自定义类型的:

typedef char CHAR;          // Character type.
typedef CHAR * PSTR;        // Pointer to a string (char *).
PSTR strchr( PSTR source, CHAR target );
typedef unsigned long ulong;
ulong ul;     // Equivalent to "unsigned long ul;"

这个比较好理解

2.指定一个结构体

typedef struct _a
{
    _a(){};
    ~_a(){};
    int fuck;
} sa, *sa

这个多说两句啊,就两句。
你这么看比较迷惑是吧,实际上你拆开看就不迷惑了

struct _a
{
    _a(){};
    ~_a(){};
    int fuck;
}

typedef _a sa, *pa;

这就比较明显了吧,sa就等于 _a, pa就等于 _a*

3.指定一个函数或者函数指针

typedef bool fuck(bool isBitch);
typedef bool (_stdcall* pfuck)(bool isBitch) ;

static fuck dog;

..fun(..)
{
    pfuck pdog = &dog;
    return ..
}

虽然看着有点怪,但是没毛病。

猜你喜欢

转载自blog.csdn.net/I_can_do_1098/article/details/53670980