利用boost变体创建具有boost::mpl::for_each的通用工厂方法
Utilize boost-variant to create generic factory method with boost::mpl::for_each
在我的一个项目中,我需要将boost::variant
which()
-函数的int
映射到boost::变体的类型。
由于某些原因,地图中没有包含正确的TVar类型?为什么?
#include <boost/mpl/for_each.hpp>
#include <boost/variant.hpp>
#include <string>
#include <map>
#include <iostream>
using TVar = boost::variant<std::string, int, double>;
namespace Helper {
struct createMap {
std::map<int, TVar> map;
template<typename T>
void operator()(const T& t) {
auto x = TVar(t);
map[x.which()] = x;
}
};
}
bool createObject(int which, TVar& var) {
Helper::createMap c;
boost::mpl::for_each<TVar::types>(boost::ref(c));
if (c.map.find(which) != c.map.end()) {
var = c.map[which];
return true;
}
else {
return false;
}
}
int main() {
TVar var;
bool ok=createObject(0, var);
return 0;
}
如果我理解正确,你想为变量分配一个默认构造的值,该值将在运行时通过索引变量的可能类型来确定,那么你正在寻找这个:
#include <boost/mpl/at.hpp>
#include <boost/mpl/size.hpp>
#include <boost/variant.hpp>
#include <string>
template <typename VariantT, int L, int R>
struct assign_default_constructed
{
static bool call(int which, VariantT& var)
{
static int const M = L + (R - L + 1) / 2;
if (which < M) {
return assign_default_constructed<VariantT, L, M - 1>::call(which, var);
}
else {
return assign_default_constructed<VariantT, M, R>::call(which, var);
}
}
};
template <typename VariantT, int I>
struct assign_default_constructed<VariantT, I, I>
{
static bool call(int /*which*/, VariantT& var)
{
//assert(which == I);
var = typename boost::mpl::at_c<typename VariantT::types, I>::type();
return true;
}
};
template <typename VariantT>
bool createObject(int which, VariantT& var)
{
static int const N = boost::mpl::size<typename VariantT::types>::value;
if (which < 0 || which >= N) return false;
return assign_default_constructed<VariantT, 0, N - 1>::call(which, var);
}
int main() {
boost::variant<std::string, int, double> var;
bool ok = createObject(1, var);
return ok ? var.which() : -1;
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- boost::进程间消息队列引发错误
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- cmake如何在fedora工作站中找到boost静态库包
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- Boost Graph Library,修复节点大小
- 什么是"#include <boost/functional/hash.hpp> "?
- 基于boost的程序的静态链接——zlib问题
- C++:如何在CLion IDE中安装Boost
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何在boost beast http请求中设置http头
- Boost Spirit,获取迭代器内部语义动作
- boost::asio::steady_timer()与sleep()我应该使用哪一个
- boost::asio如何生成多个协同程序,然后加入它们
- 当我尝试使用 sstream 和分面将 Boost Time_duration转换为字符串时,我没有得到所需的格式
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 使用Boost Interprocess创建托管共享内存需要很长时间
- Boost::posix_time::ptime舍入到给定的分钟数
- boost xml parsingl将xml的路径作为变量发送