C/C+,キーワードtypeofの使い方

3078 ワード

typeof (alternately typeOf or TypeOf) is an operator provided by several programming languages which determines the data type of a given variable. This can be useful when constructing parts of programs that need to accept many types of data but may need to take different action depending on the type of data provided.
上記引用はウィキペディア-Type ofより抜粋
Typeofは変数のデータ型を指定するために使用されます.このキーワードはsizeofに似ていますが、構造はtypedefで定義されたタイプ名に似ています.Type ofには、式またはタイプの2つの形式のパラメータがあります.
次に、式をパラメータとして使用する例を示します.
typeof(x[0](1))

ここで、xは関数ポインタ配列であると仮定する.このタイプは、関数の戻り値を記述します.
次に、パラメータとしてタイプを使用する例を示します.
typeof(int *)

このタイプではintを指すポインタについて説明します.
ISO Cプログラムに含まれるヘッダファイルでこのキーワードを使用する場合は、_typeof__typeofの代わりに.typeofは、typedefを使用できる任意の場所で使用できます.たとえば、宣言、sizeof、またはtypeofで使用できます.
typeofは宣言で式と結合するのに役立ちます.次に、最大値を取得するマクロを定義するために両者を結合します.
#define max(a,b) \
       ({ typeof (a) _a = (a); \
           typeof (b) _b = (b); \
         _a > _b ? _a : _b; })

ローカル変数に下線を使用して名前を付けるのは、式の変数名aおよびbと競合しないようにするためです.
以下にtypeofの使用例を示します.
  • yがxを指すと宣言するデータ型
  • typeof(*x) y;
  • yがxを指すデータ型を宣言する配列
  • typeof(*x) y[4];
  • はyを文字ポインタ配列
  • と宣言する.
    typeof(typeof(char *)[4]) y;

    上記の宣言はchar *y[4];に等しい
    Type ofはlinux内で広く使われています.例えば、マクロcontainer_of memberを含む構造体typeのアドレスを取得するには:
    /**
     * container_of - cast a member of a structure out to the containing structure
     *
     * @ptr:    the pointer to the member.
     * @type:   the type of the container struct this is embedded in.
     * @member: the name of the member within the struct.
     *
     */
    #define container_of(ptr, type, member) ({          \
        const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
        (type *)( (char *)__mptr - offsetof(type,member) );})

    文章の一部はhttps://gcc.gnu.org/onlinedocs/gcc/Typeof.html