Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

High level print function for C++ [duplicate]

Tags:

c++

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.

like image 777
Toàn Nguyễn Avatar asked Jun 05 '26 13:06

Toàn Nguyễn


2 Answers

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;
}
like image 172
Deedee Megadoodoo Avatar answered Jun 07 '26 01:06

Deedee Megadoodoo


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).

like image 32
Object object Avatar answered Jun 07 '26 01:06

Object object



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!