C++ 使用BOOST::fusion::size进行BOOST\u PP\u重复

C++ 使用BOOST::fusion::size进行BOOST\u PP\u重复,c++,boost-fusion,boost-preprocessor,C++,Boost Fusion,Boost Preprocessor,我想在编译时对struct进行迭代,并将迭代次数写入输出。只需提及——在实际情况中,我将在数据中传递更多参数 #include <iostream> #include <string> #include <vector> #include <boost/fusion/include/adapt_struct.hpp> #include <boost/fusion/include/size.hpp> #include <boost/

我想在编译时对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")
}
#包括
#包括
#包括
#包括
#包括
#包括
结构MyStruct
{
int x;
int-y;
};
增强融合适应结构(
我的结构,
(int,x)
(国际,y)
)
#定义打印(未使用、编号、数据)\

std::cout而不是使用
BOOST\u PP\u REPEAT
,您可以使用贯穿每个元素的
BOOST::fusion::for\u each
。例如:

#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"));
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
结构MyStruct{
int x;
int-y;
};
增强融合适应结构(
我的结构,
(int,x)
(国际,y)
)
模板
结构PrintWithData{
PrintWithData(数据数据):数据(数据){
模板
运算符()
{

std::cout这是这个问题的精确解决方案(稍后会问更一般的问题,并找到解决这个问题的answear):

大小函数应该在预处理器阶段计算,目前情况并非如此。为什么不改用fusion::for_each?在实际情况中,我想构建一个简单的开关-每个案例都是由BOOST\u PP\u REPEAT-fusion::for_each looks创建的。但是如果您可以用BOOST::fusion::for_each显示开关语句,那么我可以使用它:)(只需另外演示如何加载多个参数,以便我可以在case语句中使用它(如std::cout,但如果我理解正确,它将添加一个调用到operator())。我想使用此解决方案创建swich case,此解决方案可能比仅由编译器创建swich慢一点。我认为这是一个好的解决方案,但是否可以将boost_pp_repeat与fusion::size一起使用?在std::cout case中,它可以工作?它对操作符()进行两次调用,每个元素一次调用(但只有一次编译,使用[T=int])。它可能会为您内联此函数,所以它没有那么糟糕。正如我在评论中所说的,为了使用
boost\u pp\u repeat
深度必须在预处理器时计算,而fusion::size则在编译时计算。这根本无法做到。