Boost 预处理器传递函数中的所有结构参数

问题描述 投票:0回答:1

是否可以使用 boost 预处理器 API 在函数中传递结构体的所有成员 我有类似的东西,但无法编译。

#include <iostream>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/variadic_seq_to_seq.hpp>
#include <boost/preprocessor/seq/elem.hpp>

// Define a macro to generate code for passing a struct member to a function
#define PASS_MEMBER_TO_FUNCTION(r, structName, elem) \
    function(BOOST_PP_SEQ_ELEM(0, elem), structName.BOOST_PP_SEQ_ELEM(1, elem));

// Define a macro to iterate over struct members and pass them to a function
#define PASS_MEMBERS_TO_FUNCTION(structName, members) \
    BOOST_PP_SEQ_FOR_EACH(PASS_MEMBER_TO_FUNCTION, structName, BOOST_PP_VARIADIC_SEQ_TO_SEQ(members))

// Example struct
struct MyStruct {
    int height;
    double width;
    const char* name;
};

// Example function that takes struct members
void function(int value, double width, const char* name) {
    // Your function implementation here
    std::cout << "Value: " << value << ", Width: " << width << ", Name: " << name << std::endl;
}

int main() {
    // Usage example
    MyStruct myStruct{10, 20.5, "example"};
    PASS_MEMBERS_TO_FUNCTION(myStruct, ((int, height))((double, width))((const char*, name)));

    return 0;
}
c++ boost preprocessor
1个回答
1
投票

使用 Boost PFR,您不需要预处理器:

std::apply(function, boost::pfr::structure_tie(myStruct));

演示 在 Coliru 上直播

#include <boost/pfr.hpp>
#include <iostream>

struct MyStruct {
    int         height;
    double      width;
    char const* name;
};

// Example function that takes separate parameters
void function(int value, double width, char const* name) {
    std::cout << "Value: " << value << ", Width: " << width << ", Name: " << name << std::endl;
}

int main() {
    // Usage example
    MyStruct myStruct{10, 20.5, "example"};
    apply(function, boost::pfr::structure_tie(myStruct));
}

印刷

Value: 10, Width: 20.5, Name: example
© www.soinside.com 2019 - 2024. All rights reserved.