boost::any
을 사용할 수 있습니다. 예를 들면 : 당신이 어떤 정의 된 범위에 허용 된 유형의 집합을 제한하려면
#include <vector>
#include <boost/any.hpp>
#include <iostream>
struct my_class { my_class(int i) : x{i} { } int x; };
int main()
{
std::vector<boost::any> v;
v.push_back(42);
v.push_back(std::string{"Hello!"});
v.push_back(my_class{1729});
my_class obj = boost::any_cast<my_class>(v[2]);
std::cout << obj.x;
}
, 당신은 boost::variant
대신 사용할 수 있습니다 또한 방문 지원
#include <vector>
#include <boost/variant.hpp>
#include <iostream>
struct my_class { my_class(int i) : x{i} { } int x; };
int main()
{
typedef boost::variant<int, std::string, my_class> my_variant;
std::vector<my_variant> v;
v.push_back(42);
v.push_back("Hello!");
v.push_back(my_class{1729});
my_class obj = boost::get<my_class>(v[2]);
std::cout << obj.x;
}
boost::variant
. 아래의 수행으로
struct my_visitor : boost::static_visitor<void>
{
void operator() (int i)
{
std::cout << "Look, I got an int! " << i << std::endl;
}
void operator() (std::string const& s)
{
std::cout << "Look, I got an string! " << s << std::endl;
}
void operator() (my_class const& obj)
{
std::cout << "Look, I got a UDT! And inside it a " << obj.x << std::endl;
}
};
그리고 그것을 호출 : 당신은 변형에 가능한 모든 유형을 처리 할 수있는 방문자를 정의 할 수
다음
int main()
{
typedef boost::variant<int, std::string, my_class> my_variant;
std::vector<my_variant> v;
v.push_back(42);
v.push_back("Hello!");
v.push_back(my_class{1729});
my_visitor mv;
for (auto const& e : v)
{
e.apply_visitor(mv);
}
}
가 live example이다. boost::variant
에 대한 좋은 점은 방문자가 변형이 보유 할 수있는 모든 유형을 처리 할 수 있는지 컴파일 타임 검사를 수행한다는 것입니다.
아마도'boost :: variant'의 벡터입니다. – chris
또 다른 선택은'boost :: any' – dchhetri
이 아니라'std :: vector'가 아니라'std :: tuple' (C++ 11에서)입니다. std :: vector는 uniform 타입의 컨테이너입니다. –