【问题标题】:BOOST_PP_REPEAT with boost::fusion::size带有 boost::fusion::size 的 BOOST_PP_REPEAT
【发布时间】:2015-07-29 19:00:32
【问题描述】:

我想在编译时迭代 struct 并写入输出迭代次数。顺便提一下 - 在实际情况下,我会在数据中传递更多参数。

#include <iostream>
#include <string>
#include <vector>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>

struct MyStruct
{
    int x;
    int y;
};

BOOST_FUSION_ADAPT_STRUCT(
    MyStruct,
    (int, x)
    (int, y)    
    )

#define PRINT(unused, number, data) \
    std::cout << number << std::endl;

int main()
{
    MyStruct s;

    std::cout << boost::fusion::size(s) << std::endl;
    //line below works - it iterate and write output
    BOOST_PP_REPEAT(2, PRINT, "here I will pass my data")

    //this won't compile 
    //BOOST_PP_REPEAT(boost::fusion::size(s), PRINT, "here i will pass my data")
}

如何修复有问题的行,以便当我在结构中添加更多成员时它会起作用?我需要 C++03 的解决方案 :(

【问题讨论】:

  • 大小函数应该在预处理阶段计算,目前不是这种情况。你为什么不改用 fusion::for_each 呢?
  • 在实际情况下,我想构建简单的开关 - 每个案例都是由 BOOST_PP_REPEAT 创建的 - fusion::for_each 看起来。但是,如果您可以使用 boost::fusion::for_each 显示 switch 语句-那么我可以使用它:) (仅显示如何加载多个参数,以便我可以在 case 语句中使用它(例如 std::cout

标签: c++ boost-fusion boost-preprocessor


【解决方案1】:

您可以使用boost::fusion::for_each,而不是使用BOOST_PP_REPEAT,它会遍历每个元素。示例:

#include <iostream>
#include <string>
#include <vector>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>

struct MyStruct {
    int x;
    int y;
};

BOOST_FUSION_ADAPT_STRUCT(
    MyStruct,
    (int, x)
    (int, y)
)

template<typename Data>
struct PrintWithData {
    PrintWithData(Data data) : data(data) {}

    template<typename T>
    operator()(const T& thingToBePrinted)
    {
        std::cout << thingToBePrinted << std::endl;
    }

    Data data;
};

int main()
{
    MyStruct s;
    //this will compile
    boost::fusion::for_each(s, PrintWithData<std::string>("here I will pass my data"));
}

【讨论】:

  • 此解决方案有效,但如果我理解正确,它会再添加一个调用 - 到 operator()。我想使用这个解决方案来创建 swich 案例,这个解决方案可能比只通过编译器创建 swich 慢一些。我认为这是一个很好的解决方案,但是是否可以将 boost_pp_repeat 与 fusion::size 一起使用 - 在 std::cout 的情况下它正在工作?
  • 它对 operator() 进行了两次调用,每个元素调用一次(但只有一个已编译,使用 [T=int])。它可能会为你内联这个函数,所以还不错。正如我在评论中所说,为了使用boost_pp_repeat,深度必须在预处理器时计算,而 fusion::size 在编译时计算。根本做不到。
【解决方案2】:

这里是这个问题的确切解决方案(稍后问了更一般的问题,并找到了解决这个问题的答案):https://stackoverflow.com/a/31713778/4555790

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多