只是为了好玩,这里有两个可变参数 C++11 实现print
:一个在参数之间插入空格,一个不插入。(住在ideone。)
#include <iostream>
namespace with_spaces {
namespace detail {
std::ostream& print(std::ostream& os) {
return os;
}
template <typename T>
std::ostream& print(std::ostream& os, T&& t) {
return os << std::forward<T>(t);
}
template <typename T, typename U, typename... Args>
std::ostream& print(std::ostream& os, T&& t, U&& u, Args&&... args) {
return print(print(os, std::forward<T>(t)) << ' ', std::forward<U>(u), std::forward<Args>(args)...);
}
}
template <typename... Args>
void print(Args&&... args) {
detail::print(std::cout, std::forward<Args>(args)...) << std::endl;
}
}
namespace without {
namespace detail {
std::ostream& print(std::ostream& os) {
return os;
}
template <typename T>
std::ostream& print(std::ostream& os, T&& t) {
return os << std::forward<T>(t);
}
template <typename T, typename... Args>
std::ostream& print(std::ostream& os, T&& t, Args&&... args) {
return print(print(os, std::forward<T>(t)), std::forward<Args>(args)...);
}
}
template <typename... Args>
void print(Args&&... args) {
detail::print(std::cout, std::forward<Args>(args)...) << std::endl;
}
}
#include <iomanip>
int main() {
std::cout << std::boolalpha;
with_spaces::print(1, "foo", new int(3), 0xFFFFFFFFFFULL, 42, 0 == 1);
without::print(1, "foo", new int(3), 0xFFFFFFFFFFULL, 42, 0 == 1);
}
让我感兴趣的是,要完成这个简单的单行宏可以做什么,需要多少代码。