gpt4 book ai didi

c++ - 字符串化任意数量的变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:22:05 25 4
gpt4 key购买 nike

对于单个变量(或给定数量的变量),很容易使用宏来对变量进行字符串化。例如。对于 2 个变量,我可以这样做:

#define STRINGIFY(var1, var2) (std::string(#var1) + " " + #var2)

有没有一种方法可以使用可变参数宏或某种其他类型的编译时技巧来扩展上述内容,以最终获得接受任意数量参数的 STRINGIFY 函数?

最佳答案

我不确定我是否理解您要尝试做的事情。下面的代码在编译时标记化了 __VA_ARGS__。它不检查语法:它盲目地将空格和逗号替换为 '\0',将标识符的开头存储在 arg 中,并将参数数量存储在 argc

#include <iostream>

template < unsigned N > constexpr
unsigned countarg( const char( &s )[N], unsigned i = 0, unsigned c = 0 )
{
return
s[i] == '\0'
? i == 0
? 0
: c + 1
: s[i] == ','
? countarg( s, i + 1, c + 1 )
: countarg( s, i + 1, c );
}

template < unsigned N > constexpr
unsigned skipid( char( &s )[N], unsigned i = 0 )
{
return s[i] == '\0' || s[i] == ' ' || s[i] == '\t' || s[i] == ','
? i
: skipid( s, i + 1 );
}

template < unsigned N, unsigned M > constexpr
unsigned tokenize( char( &s )[N], const char*(&a)[M], unsigned i = 0, unsigned j = 0 )
{
return s[i] == '\0'
? i
: s[i] == ' ' || s[i] == '\t' || s[i] == ','
? ((s[i] = '\0'),
tokenize( s, a, ++i, j ))
: ((a[j] = s + i),
i = skipid( s, i ),
tokenize( s, a, i, ++j ));
}

#define TOKENIZEVA( ... ) char orig[] = #__VA_ARGS__; const unsigned argc = countarg(#__VA_ARGS__); const char* arg[argc]; tokenize( orig, arg );

#define PRINT( ... ) { TOKENIZEVA(__VA_ARGS__) for ( auto s : arg ) std::cout << s << std::endl; }

int main()
{
PRINT( first, second, third, fourth );
return 0;
}

关于c++ - 字符串化任意数量的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35802830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com