【问题标题】:A std::map like container that maps types to values将类型映射到值的类似 std::map 的容器
【发布时间】:2023-03-05 08:35:01
【问题描述】:

我正在寻找混合元容器/容器类。我想要一个将编译时类型映射到运行时值的类。一个代码片段价值 1024 个字,所以:

struct Foo { /* ... */ };
struct Bar { /* ... */ };

int main()
{
   meta_container<Foo,float,int> mc;
   mc.get<float>() = 1.0f;
   mc.get<Foo>().method(blah);
   mc.get<Bar>(); //compiler error
}

这真是无聊的东西。使用可变参数模板的实现会很有趣,但接口非常简单。

让这变得更加困难的部分是我想要的最后一个功能。

void foo( const meta_constainer<Foo,Bar,Baz>& mc );

//make_mc is sorta like make_pair or make_tuple.

int main()
{
   foo( make_mc(Foo(), Bar(), Baz()) );  // not really interesting
   foo( make_mc(Bar(), Foo(), Baz()) );  // this is more challenging
   foo( make_mc(Foo()) );  // this might be difficult as well.
}

我可以编写这样一个容器,但我想找到一个已经编写/调试过的容器。我最大的绊脚石是缺乏好的关键字来搜索(异构容器不是我想要的)。

是否有具有此或类似接口的 Boost 库?

这个东西叫什么,所以我可以更有效地用谷歌搜索它?


更新:

我不是在寻找:

  • boost::mpl::map
    这会将编译时值映射到编译时值
  • std::map&lt;*,boost::any&gt;
    这会将静态类型运行时值映射到动态类型运行时值
  • std::map&lt;*,boost::variadic&lt;*&gt;&gt;
    这会将静态类型的运行时值映射到变量类型的运行时值
  • std::map&lt;typeid,boost::variadic&lt;*&gt;&gt;
    这与我想要的很接近,只是它使用 RTTI 并且如果使用错误的类型访问它不是编译错误。

【问题讨论】:

    标签: c++ templates metaprogramming


    【解决方案1】:

    【讨论】:

    • boost::fusion::set 做得比我想要的多,但它是迄今为止我见过的最好的。它需要对参数进行排序,所以我的无序列表示例不起作用。
    • 嗯,我原以为 fusion::vector 是你要找的东西?您可以将其与枚举结合起来以实现您的要求吗?
    • fusion::set 允许我将int 映射到一个整数值,并将float 映射到一个浮点值。 fusion::vector 将编译时 0 映射到整数值,将编译时 1 映射到浮点值。我可以在0,1 常量和int,float 之间进行辅助映射,但fusion::set 已经为我做了。
    • 我想唯一的缺点是,你不能多次出现相同的类型,但如果你不需要,那么 set 就可以了......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    相关资源
    最近更新 更多