【问题标题】:Provide input for constant argument count macro from variable argument count macro in Visual Studio从 Visual Studio 中的可变参数计数宏为常量参数计数宏提供输入
【发布时间】:2014-01-03 09:57:39
【问题描述】:

我想定义一个宏,它将为每个不是前缀的参数添加前缀。

我定义了一些常量参数计数宏,然后定义了一个使用可变参数来调用其他宏。我的问题是 varadic 宏没有为常量宏提供正确的输入。

#define prefix2(pefixV, a1, a2) pefixV##a1, pefixV##a2
#define prefix3(pefixV, a1, a2, a3) prefix2(pefixV, x, y)##, ##pefixV##z

#define prefixX(count, pefixV, ...) prefix##count(pefixV, __VA_ARGS__)

//MacroTester from stackoverflow
#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)
#define TESTE EXPAND_AND_QUOTE(TEST)

int main(int argc, const char* argv[])
{
    #define TEST prefixX(2, simplePrefix, X, Y)
    static_assert(false, TESTE);

    return 0;
}

静态断言打印:static assertion failed with "simplePrefixX, Y, simplePrefix"

我的预期结果是simplePrefixX, simplePrefixY 有没有办法强制可变参数宏提供正确的输入?

我可以在这个项目中使用 Visual Studio 2012 或 2013

【问题讨论】:

  • 您可以考虑使用BOOST_PP_OVERLOAD,这样您就不必将计数传递给prefixX

标签: c++ visual-studio macros


【解决方案1】:

我找到了解决办法。

#define prefix2(pefixV, a1, a2) pefixV##a1, pefixV##a2
#define prefix3(pefixV, a1, a2, a3) prefix2(pefixV, x, y)##, ##pefixV##z

#define macroMagic(x) x

#define prefixX(count, pefixV, ...) macroMagic(prefix##count(pefixV, __VA_ARGS__))

//MacroTester from stackoverflow
#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)
#define TESTE EXPAND_AND_QUOTE(TEST)

int main(int argc, const char* argv[])
{
    #define TEST prefixX(2, simplePrefix, X, Y)
    static_assert(false, TESTE);

    return 0;
}

之所以有效,是因为macroMagicprefix##count 之前被调用,它会将__VA_ARGS__ 从解释为一个不可分割的元素的X, Y 更改为XY 作为单独的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 2012-07-04
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    相关资源
    最近更新 更多