C++1z なんでも代入できるanyクラス

C++1zでは、コピー可能かムーブ可能であればどんな型でも代入できるanyクラスが入ります。C++には全ての型の継承元のobjectクラスというものはないので、その代わりにこのクラスを使えます。

このクラスのために、<any>ヘッダが新規追加されます。

#include <iostream>
#include <any>
#include <string>

int main()
{
  std::any a = 3; // int値を代入
  a = std::string("hello"); // stringオブジェクトを代入

  // 中身を取り出す
  // 取り出せなかったらstd::bad_any_cast例外
  try {
    std::string s = std::any_cast<std::string>(a);
    std::cout << s << std::endl;
  }
  catch (std::bad_any_cast& e) {
    std::cout << "bad_any_cast" << std::endl;
  }

  // 中身を取り出す
  // こちらは取り出せなかったらヌルポインタが返る
  if (std::string* s = std::any_cast<std::string>(&a)) {
    std::cout << *s << std::endl;
  }
  else {
    std::cout << "null" << std::endl;
  }
}

出力:

hello
hello

Boostと標準の差異

標準に採択されたanyは、Boostにあるanyとほぼ同じです。Boost 1.61.0時点のanyとの差異は、constexpr対応していることに加え、optionalvariantと共通の設計にするために、標準側に以下の機能があるくらいです:

この共通設計のために、Boostにある以下のメンバ関数はありません:

参照

お断り

この記事の内容は、C++1zが正式リリースされる際には変更される可能性があります。正式リリース後には、C++日本語リファレンスサイトcpprefjpの以下の階層の下に解説ページを用意する予定です。