【发布时间】:2017-10-13 08:09:06
【问题描述】:
可以创建一个宏 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));
}
有没有一种简单的方法来打印 variable 数量的参数,每个参数的名称都在前面?即从以下实现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);
}
【问题讨论】: