找出可变参数宏中 __VA_ARGS__ 的类型

Find out the type of __VA_ARGS__ in a variadic macro

据推测,我有一个可变参数宏(例如,MY_MACRO(...)),我按以下方式调用它:

MY_MACRO(std::pair<int, int> const &p)

现在,我的宏正文中的 __VA_ARGS__ 将是 std::pair<int, int> const &p

有没有办法找出__VA_ARGS__的类型?

大概,如果像 decltype(std::pair<int, int> const &p) 这样的东西工作并产生 std::pair<int, int> const&,我将不胜感激,所以在我的可变参数宏的主体中 decltype(__VA_ARGS__) 也会产生 std::pair<int, int> const&。不幸的是,这不起作用。

您可以使用 __VA_ARGS__ 作为 lambda 参数,然后将该 lambda 转换为函数指针并提取参数类型:

template <typename T> struct func_param {};
template <typename T> struct func_param<void(*)(T)> {using type = T;};

#define FOO(...) \
    do \
    { \
        auto lambda = +[]([[maybe_unused]] __VA_ARGS__) {}; \
        using type = func_param<decltype(lambda)>::type; \
        /* Do something with `type`. */\
    } \
    while (0);