它可以创建一个宏str(a)
将使用它的参数(a
)和它的字符串化的名称(#a
),例如:如何获得可变宏中每个参数的名称?
#include <iostream>
#define str(a) #a, " ", a
int main()
{
int i = 5;
float f = 4.5;
const char* s = "string";
auto l = [] (const auto&... p) { (std::cout << ... << p) << std::endl; };
l(str(i));
l(str(f));
l(str(s));
}
是否有一个简单的方法来打印变量参数的数量前加上每个参数的名称?即实现从以下PREPEND_EACH_ARG_WITH_HASH_ARG
:
#include <iostream>
#include <tuple>
template <typename ... Ts>
void print_all(const Ts&... ts)
{
(std::cout << ... << ts) << std::endl;
}
#define PREPEND_EACH_ARG_WITH_HASH_ARG(...) // how to implement '#a, " ", a' here?
#define PRINT_ALL(...) print_all(PREPEND_EACH_ARG_WITH_HASH_ARG(__VA_ARGS__))
int main()
{
auto a = 10;
auto b = 20.1;
auto c = "string";
auto d = 'c';
PRINT_ALL(a, b, c, d);
}
IOW,自己重新实现Boost.Preprocessor的那一点:-) – Angew
@Angew是或多或少:)我不确定Boost库究竟是如何实现的(它可能比我的例子更智能一些)。我通常喜欢独立于第三方库,所以我认为这个解决方案值得一提。 – Banan
@Banan,感谢您的解释,但是接受提升为答案的参考,因为它更“简单”:) –