【问题标题】:boost::mpl for_each with normal 'C' Arrayboost::mpl for_each 与普通的“C”数组
【发布时间】:2010-01-01 03:01:37
【问题描述】:

使用 boost::mpl,我可以创建一个三元素向量的 typedef,如下所示:

typedef boost::mpl::vector_c<int,1,2,3> height_t;

我可以使用以下代码段从这个 typedef 中提取值:

std::vector<int> height;
boost::mpl::for_each<height_t>(boost::bind(&std::vector<int>::push_back, &height, _1));   

assert(height[0] == 1);
assert(height[1] == 2);
assert(height[2] == 3);

我想知道是否有办法做同样的事情,但使用普通的“C”数组而不是std::vector。不幸的是,我不能在这个项目中使用 STL 容器。

uint32_t height[3];
boost::mpl::for_each<height_t>(????, &height, _1));    

我怀疑我需要更换 ????与另一个绑定子句。有什么想法吗?

【问题讨论】:

  • 不应将其标记为“C”。 C 和 C++ 是不同的语言。

标签: c++ boost stl boost-mpl


【解决方案1】:

试试类似的东西

 struct foo { 
     int c;
     int* arr;
     template<class U> 
     void operator(U& u) { arr[c++] = u; }
     foo(int a*) : c(0), arr(a) {}
 };

 for_each<height_t>(foo(height));

【讨论】:

  • 通过引用获取数组会比让它衰减到指针更好,例如template&lt;int n&gt; struct foo { int (&amp;arr)[n]; foo(int (&amp;a)[n]) : arr(a) {} };
【解决方案2】:

是的,你的想法会奏效。我稍微重写了一遍。但是,我想知道是否有一种方法可以使用 inplace 仿函数,使用 bind 和 lambda 来做同样的事情。同时,我会采纳你的想法。

模板 结构静态分配 { 类型_t*一个; static_assign(type_t* a) : a(a) {} 模板 无效运算符()(T t) { *a++ = t; } }; uint32_t 颜色[MAX_COLORS]; uint32_t* pcolor = (uint32_t*)&color; boost::mpl::for_each::type>(static_assign(pcolor)); pcolor += 指标;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多