BOOST_PP_REPEAT with boost::fusion::size

BOOST_PP_REPEAT with boost::fusion::size

本文关键字:fusion size boost with PP REPEAT BOOST      更新时间:2023-10-16

我想在编译时遍历结构体并写入迭代的输出次数。只是提一下——在实际情况下,我将在data中传递更多的参数。

#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的解决方案:(

您可以使用遍历每个元素的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"));
}

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