如何使std :: cout的可变宏? [英] How to make a variadic macro for std::cout?
本文介绍了如何使std :: cout的可变宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何创建一个带有可变参数的宏,并使用std :: cout打印出来?
How would I make a macro that took a variable amount of arguments, and prints its out using std::cout? Sorry if this is a noob question, couldn't find anything that clarified variadic macros after searching around for the answer.
概念示例:
#include <iostream>
#define LOG(...) std::cout << ... << ... << std::endl
int main() {
LOG("example","output","filler","text");
return 0;
}
会输出:
exampleoutputfillertext
推荐答案
你不需要预处理器宏来做到这一点。你可以写成普通的
C ++:
You do not need preprocessor macros to do this. You can write it in ordinary C++:
#include <iostream>
#include <utility>
void log(){}
template<typename First, typename ...Rest>
void log(First && first, Rest && ...rest)
{
std::cout << std::forward<First>(first);
log(std::forward<Rest>(rest)...);
}
int main()
{
log("Hello", "brave","new","world!\n");
log("1", 2,std::string("3"),4.0,'\n');
}
输出:
Hellobravenewworld!
1234
您应该研究可变参数模板
和参数包
而不是可变参数宏,这在现代C ++中很少有用。
You should research variadic templates and parameter packs rather than variadic macros, which are rarely useful in modern C++.
(gcc 4.9.2 -std = c ++ 11)
(gcc 4.9.2 -std=c++11)
这篇关于如何使std :: cout的可变宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文