varargs宏以执行函数调用或将其转换为字符串
Varargs macro to either execute a function call or convert it to a string
我想选择调用函数或将其转换为字符串(打印出)。以下是行不通的:
#if !defined(ENABLE_FUNCS)
#define APPLY(func, ...) do { (func(__VA_ARGS__); } while(0)
#else
#define APPLY(func, ...)
do {std::clog << #func << #__VA_ARGS__ << std::endl;} while(0)
#endif
...
APPLY(openlog, ((name.size() ? name.data() : nullptr), flags, facility);
有什么想法?
如果您可以使用variadic模板而不是VA_ARGS
,请考虑ENABLE_FUNCS
情况的以下定义:
template <typename F, typename... Args>
void apply(F&& f, Args&&... args) {
std::initializer_list<int> l{
(std::forward<F>(f)(std::forward<Args>(args)), 0)...
};
(void) l; // Silence compiler warnings
}
std::initializer_list
为我们提供了一种以给定顺序在每个参数上调用 f
的方法。我们正在使用逗号操作员使用一些黑客攻击,以使表达式评估为int
,以便为任何返回类型f
都可以很好地定义l
。
最后,如果未定义ENABLE_FUNCS
,则可以提供apply
的此定义:
template <typename F, typename... Args>
void apply(F&&, Args&&... args) {
std::initializer_list<int> l{
(cout << std::forward<Args>(args), 0)...
};
cout << endl;
(void) l;
}
我们使用initializer_list
的策略与以前相同的策略,但是在这种情况下,我们将每个参数转发给您的记录器。
相关文章:
- wcstombs_s(),转换字符串的长度
- 使用 CStringW/CStringA 和 CT2W/CT2A 转换字符串有什么区别?
- 无法转换字符串插入函数的参数
- 转换字符串向量:基于先前的值跳过元素
- 从中间器转换字符串不起作用,出了什么问题?
- 失败的证明转换字符串到枚举类
- 如何使用正则表达式和提升转换迭代器标记和转换 c 字符串
- 使用java jni时转换字符串类型
- 如何避免在转换字符串令牌流时重复istringstream构造
- 阿托伊未正确转换字符串
- C++,转换字符串,使连续下划线序列变为单个下划线
- 使用长算术转换字符串
- 转换字符串十进制数时的精度
- 将词法转换字符串提升为双精度
- 使用marshal_as函数转换字符串的性能
- C++不会从数据转换字符串
- 无论如何,在c++ /Qt中转换字符串到结构中的字段
- C++ 隐式类型转换字符串 -> int?
- 转换字符串到浮点数,c++实现
- 用于转换字符串大小写的函数