gpt4 book ai didi

c++ - BOOST_PP_REPEAT 与 boost::fusion::size

转载 作者:行者123 更新时间:2023-11-28 02:23:00 26 4
gpt4 key购买 nike

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

#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"));
}

关于c++ - BOOST_PP_REPEAT 与 boost::fusion::size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31708960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com