boost any

Boost Any provides the class boost::any which like JavaScript variables can store arbitrary types of information.

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

int main() {
  boost::any a = 1;
  std::cout << boost::any_cast<int>(a) << std::endl;
  if (!a.empyt()) {
    const std::type_info& ti = a.type();
    std::cout << ti.name() << std::endl;
  }
  a = 3.14;
  std::cout << boost::any_cast<double>(a) << std::endl;
  a = true;
  std::cout << std::boolalpha << boost::any_cast<bool>(a) << std::endl;
  return 0;
}

Variables of type boost::any are not completely unlimited in what they can store; Any value stored in a variable of type boost::any must be copy-constructible.

By passing the appropriate type as a template parameter to boost::any_cast, the value of the variable is converted. If an invalid type is specified, an exception of type boost::bad_any_cast will be thrown.

To check whether or not a variable of type boost::any contains information, use the member function empty(). To check the type of the stored information, use the member function type().

猜你喜欢

转载自www.cnblogs.com/sssblog/p/11058406.html