2007-07-24

[]型を数値で管理してキャスト

型をキャストする関数配列の要素として管理。

std::vectorを使えば動的に追加、削除も可能。

// 仕組みとしては, tempalteでキャストする型が

// コンパイル時に決められた関数ポインタを突っ込むだけ.

// templateな関数でもその具体的な型はコンパイル前に一意に決めることが出来る.

#include <vector>

class asdf{virtual void f(){}};

class fdsa{virtual void f(){}};

//各関数はinline期待可能!?

class zxcv : asdf{

  //関数ポインタを得る為, staticなメンバでなければならない.

  template<typename T> static bool castor(zxcv *a){

    return (bool)dynamic_cast<T*>(a);

  }

  typedef bool(*castorfunc_t)(zxcv*);

  std::vector<castorfunc_t> castorFunc_Array;

public:

  int get_typeLength(){

    return (int)castorFunc_Array.size();

  }

  bool test(int i){

    return (castorFunc_Array[i])(this);

  }

  template<typename T>void push_type(T){

    castorFunc_Array.push_back(castor<T>);

  }

};

int main(){

  asdf a;

  fdsa f;

  zxcv z;

  z.push_type(a);

  z.push_type(f);

  printf("asdf <- z %s\n", z.test(0) ? "true" : "false");

  printf("fdsa <- z %s\n", z.test(1) ? "true" : "false");

  return 0;

}

記事への反応(ブックマークコメント)

ログイン ユーザー登録
ようこそ ゲスト さん