Is there a way to create a function or a macro in C++ that you can use like Python? What i mean is a function like:
print(i); // i is an integer.
print(i, s); // i is an integer, s is a std::string. They are separated by a white space.
A function that takes in a number of arguments, then just prints them out regardless of the types.
If you are allowed to use C++17, you can do it using fold-expression, like this:
#include <iostream>
template<class ...Args>
void print(const Args &...args) {
auto seq_started = false;
auto print_impl = [&](auto &value) mutable {
if (seq_started) {
std::cout << " " << value;
} else {
seq_started = true;
std::cout << value;
}
};
(print_impl(args), ...);
}
int main() {
print("foo", 10, "bar", 20, "baz");
return 0;
}
Use streams:
std::cout << i << ' ' << s << '\n';
For more complex formatting consider fmt, it supports the syntax for python's str.format as well as printf style formatting (but typesafe).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With