简体   繁体   English

在C ++中为每个可变参数宏参数加上一个函数参数的名称

[英]Prepend each variadic macro argument with a name of a function parameter in C++

I have a macro that is used inside of a class definition for defining as_tuple() member functions. 我有一个在类定义内部用于定义as_tuple()成员函数的宏。

#define DEFINE_AS_TUPLE(...) \
    auto as_tuple() const \
    { \
        return std::tie(__VA_ARGS__); \
    } \
    auto as_tuple() \
    { \
        return std::tie(__VA_ARGS__); \
    }

but I'd like to have a macro for defining class_as_tuple functions outside of a class. 但我想拥有一个宏,用于在类外部定义class_as_tuple函数。 In common it should look like this: 共同点应该看起来像这样:

#define DEFINE_AS_TUPLE_OUTSIDE_OF_CLASS(ClassName, ...) \
    inline auto class_as_tuple(const ClassName & val) \
    { \
        return std::tie(__VA_ARGS__); \
    } \
    inline auto class_as_tuple(ClassName & val) \
    { \
        return std::tie(__VA_ARGS__); \
    } \

but it is not clear how to prepend VA_ARGS with 'val.' 但目前尚不清楚如何在VA_ARGS前面加上“ val”。 in std::tie() call. 在std :: tie()调用中。

To make the question more clear I provided an example of how my first macro is used: 为了使问题更清楚,我提供了一个有关如何使用第一个宏的示例:

class B
{
public:

    B() : m_set{ 0, 1, 2 }, m_v{3, 4}
    {
    }

    DEFINE_AS_TUPLE(m_set, m_v, m_u8, m_b)

private:

    std::set<int> m_set;
    std::vector<int> m_v;

    uint8_t m_u8 = 25;

    bool m_b = true;
};

but I also need: 但我还需要:

DEFINE_AS_TUPLE_OUTSIDE_OF_CLASS(B, m_set, m_v, m_u8, m_b)

The pragmatic approach would be to type out (or possibly generate) a macro for each number of parameters you care about. 实用的方法是为您关心的每个参数键入(或可能生成)宏。 Given that you might not need to "tuplify" more than eg 10 members and that this pattern is apparently common enough in your code to warrant a macro like this, writing them out by hand may be the easiest way. 鉴于您可能不需要“简化”(例如)10个以上的成员,并且这种模式在您的代码中显然足够普遍,可以保证像这样的宏,那么手工写出它们可能是最简单的方法。 For example: 例如:

#define DEFINE_AS_TUPLE_OUTSIDE_OF_CLASS_2(ClassName, a, b) \
    inline auto class_as_tuple(const ClassName& val) \
    { \
        return std::tie(val.a, val.b); \
    } \
    inline auto class_as_tuple(ClassName& val) \
    { \
        return std::tie(val.a, val.b); \
    }

#define DEFINE_AS_TUPLE_OUTSIDE_OF_CLASS_3(ClassName, a, b, c) \
    inline auto class_as_tuple(const ClassName& val) \
    { \
        return std::tie(val.a, val.b, val.c); \
    } \
    inline auto class_as_tuple(ClassName& val) \
    { \
        return std::tie(val.a, val.b, val.c); \
    }

However, this does not work in your given example as all the members are private. 但是,这在您给定的示例中不起作用 ,因为所有成员都是私有成员。 You'd have to make these into friend functions, so you'd need a macro for that, in which case you could just write class_as_tuple using val.as_tuple() ... 您必须将它们变成friend函数,因此需要一个宏,在这种情况下,您可以使用val.as_tuple()编写class_as_tuple

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

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