BOOST_PP_REPEAT with boost::fusion::size
BOOST_PP_REPEAT with boost::fusion::size
我想在编译时遍历结构体并写入迭代的输出次数。只是提一下——在实际情况下,我将在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
相关文章:
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 大于65535的C++数组[size]引发不一致的溢出
- 为什么(-1)%vector::size()总是返回0
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- vector.size() 在比较中意外工作
- vector.back() 和 vector[vector.size() - 1] 之间的区别?
- 返回 str vs. str.substr(0,str.size()) 在 leetcode 中给了我不同的输出
- 为什么 GCC 不能假设 std::vector::size 在这个循环中不会改变?
- 为什么"(!v.empty())"比"(v.size() >0)"好?
- OpenGL 在 VMWare Fusion 版本 10.1.3 上安装的虚拟机 (Ubuntu 16.04) 上崩溃
- 将"boost::tuple "转换为"boost::fusion::tuple&quo
- 迭代器库中的 std::size() 不适用于传递给函数的 C 样式数组
- std::string.size() 未知行为
- 为什么gmp会在这里与"invalid next size"重新定位一起崩溃?
- 为什么我会"Invalid read of size 8"?(瓦尔格林德)
- 从 std::string 到 std::array<char,size> 的 memcopy 额外数据是否是一种未定义的行为?
- BOOST_PP_REPEAT with boost::fusion::size