Monday, October 30, 2017

C++17: tagged union container

C++17 added a tagged union container. It is called std::variant. Here is an example:

#include <iostream>
#include <variant>

int main()
{
  std::variant<short, int, std::string> myVariant;

  myVariant = (short)1;

  std::cout << std::get<short>(myVariant) << " ";
  std::cout << std::get<0    >(myVariant) << " ";

  myVariant = 2;
  std::cout << std::get<int>(myVariant) << " ";
  std::cout << std::get<1  >(myVariant) << " ";

  myVariant = std::string("Three");
  std::cout << (std::get<std::string>(myVariant)).c_str() << " ";
  std::cout << (std::get<2          >(myVariant)).c_str() << " ";

  std::cout << std::endl;
  return 0;
}
// Output: 1 1 2 2 Three Three
References:
https://en.wikipedia.org/wiki/C%2B%2B17
http://en.cppreference.com/w/cpp/utility/variant

No comments:

Post a Comment