gpt4 book ai didi

c++ - 预声明类型定义的 boost::variant

转载 作者:行者123 更新时间:2023-11-30 02:56:46 25 4
gpt4 key购买 nike

如何编译以下内容:

typedef std::pair<std::string, Container> Structure;

typedef boost::variant<std::vector<int>, std::vector<std::string>, std::vector<Structure> > Container;

最佳答案

这是通过 liveworkspace.org/code/3BDk6v$0 链接到上面的 Angew 解决方案

#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <boost/variant.hpp>


typedef boost::make_recursive_variant<
std::vector<int>,
std::vector<std::string>,
std::vector< std::pair<std::string, boost::recursive_variant_> >
>::type Container;

typedef std::pair<std::string, Container> Structure;

struct printer: boost::static_visitor<>
{
void operator()(const std::vector<int>& vec) const
{
for(const auto elem : vec)
std::cout << elem << std::endl;
}
void operator()(const std::vector<std::string>& vec) const
{
for(const auto& elem : vec)
std::cout << elem << std::endl;
}
void operator()(const std::vector<Structure>& vec) const
{
for(const auto& elem : vec)
{
std::cout << "First:" << std::endl;
std::cout << elem.first << std::endl;
std::cout << "Second:" << std::endl;
boost::apply_visitor(*this,elem.second);
}
}
};


int main()
{
std::vector<Container> c_vec;
std::vector<int> int_vec;
int_vec.push_back(1);
int_vec.push_back(2);
Container c(int_vec);
Structure s=std::make_pair(std::string("name"),c);
std::vector<Structure> s_vec;
s_vec.push_back(s);
c_vec.push_back(int_vec);
c_vec.push_back(s_vec);

for(auto const& elem : c_vec)
boost::apply_visitor(printer(),elem);
return 0;
}

关于c++ - 预声明类型定义的 boost::variant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15219543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com