boost::any

boost::anyで何型でも入る変数を作れる。

参考

内部の実装についても詳しく書かれていて勉強になったが、templateはなんとなくわかるけどそもそもC++でclass設計をしたことが無いからよくわからない


test.cpp

#include <iostream>
#include <string>
#include <boost/any.hpp>
#include <vector>

using namespace std;
using namespace boost;

int main(int argc, char* argv[]){
  vector<any> v;
  v.push_back(15);
  v.push_back(string("test"));
  v.push_back((char*)"hello");
  v.push_back(3.1415926535897932);

  for(int i=0; i < v.size(); i++){
    any a = v[i];
    if(a.type() == typeid(int)) cout << "int: " << any_cast<int>(a) << endl; // 元の型情報
    else if(a.type() == typeid(double)) cout << "double: " << any_cast<double>(a) << endl;
    else if(a.type() == typeid(string)) cout << "string: " << any_cast<string>(a) << endl;
    else if(a.type() == typeid(char*)) cout << "char*: " << any_cast<char*>(a) << endl;
    cout << a.type().name() << endl;
  }

  return 0;
}


コンパイル

g++ -O test.cpp  -o test -I/opt/local/include/boost


実行

int: 15
i
string: test
Ss
char*: hello
Pc
double: 3.14159
d


いちいちif文でany.type()とtypeid(型名)を比較しないとならないのが面倒だな。
a.type().name()すると型名?を文字列で得られるけど、使ってる型の数だけif文を書かないで済むようにしたい


どうやらSsとかPcはコンパイラが型名を管理するためにつけている物で、環境毎に違うらしい
C++ のシンボルをデマングルする - bkブログ