简体   繁体   English

Boost.Fusion中的C ++ Variadic宏?

[英]C++ Variadic Macros in Boost.Fusion?

So, according to this answer , C++ doesn't support variadic macros, and the C++ standard doesn't mention variadic macros anywhere. 因此,根据这个答案 ,C ++不支持可变参数宏,而C ++标准在任何地方都没有提到可变参数宏。 I know that C99 introduced variadic macros with __VA_ARGS__ , and certain C++ compilers (like GCC) even provide extensions to allow this in C++, but the fact remains that variadic macros simply aren't part of standard C++. 我知道C99引入了带__VA_ARGS__可变参数宏,而某些C ++编译器(如GCC)甚至提供了在C ++中允许这种扩展的扩展,但事实上可变宏只是不是标准C ++的一部分。

Now, there's a feature in Boost.Fusion where you can bind a Fusion sequence to an arbitrary class or struct using the BOOST_FUSION_ADAPT_STRUCT macro. 现在,Boost.Fusion中有一个功能,您可以使用BOOST_FUSION_ADAPT_STRUCT宏将Fusion序列绑定到任意类或结构。 This allows you to use your class or struct as if it was a Fusion sequence. 这允许您使用您的类或结构,就像它是Fusion序列一样。

Here is an example of how this is used (taken from the Boost docs): 以下是如何使用它的示例(取自Boost文档):

namespace demo
{
    struct employee
    {
        std::string name;
        int age;
    };
}

// demo::employee is now a Fusion sequence
BOOST_FUSION_ADAPT_STRUCT(
    demo::employee,
    (std::string, name)
    (int, age))

Now, how is this code possible without variadic macros? 现在,如果没有可变参数宏,这段代码怎么可能? The BOOST_FUSION_ADAPT_STRUCT macro seems to take an arbitrary number of arguments, since presumably it can work with any arbitrary user-defined class or struct. BOOST_FUSION_ADAPT_STRUCT宏似乎采用了任意数量的参数,因为它可能适用于任意用户定义的类或结构。

I know that Boost is famous for bending C++ in interesting ways, but this seems outright impossible without compiler support. 我知道Boost以有趣的方式弯曲C ++而闻名,但如果没有编译器支持,这似乎是完全不可能的。 So what sort of wizardry is Boost.Fusion doing to pull this off? 那么什么样的魔法是Boost.Fusion做到这一点呢?

PS: Yes, I know Boost is open source. PS:是的,我知道Boost是开源的。 The first thing I did was to look at the source code. 我做的第一件事就是查看源代码。 It seems to be using the Boost Preprocessor library to somehow concatenate macros. 它似乎使用Boost预处理器库以某种方式连接宏。 But I don't understand how this can work for any arbitrary number of arguments, and the source code is a very dense collection of preprocessor code which is very difficult to understand. 但是我不明白这对于任意数量的参数是如何工作的,而源代码是一个非常密集的预处理器代码集合,很难理解。

BOOST_FUSION_ADAPT_STRUCT(
    demo::employee,
    (std::string, name)
    (int, age))

This is a single macro which takes two arguments: Argument 1: demo::employee Argument 2: (std::string, name)(int, age) 这是一个带有两个参数的宏:参数1:demo :: employee参数2:(std :: string,name)(int,age)

Argument 2 is concatenated with a string to form another macro invocation which also takes 2 parameters: 参数2与字符串连接以形成另一个宏调用,该调用也需要2个参数:

BOOST_FUSION_SOME_INTERNAL_MACRO(std::string, name)
BOOST_FUSION_SOME_INTERNAL_MACRO(int, age)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM