David G
David G

Reputation: 96810

Wrapping std::cout in a function call

I have a lot of couts and so I would like to be able to make a function that can take just three arguments. The function would print them out to the screen just as cout does like this:

print( 5, " is a ", "number" );

// should do the same thing as

cout << 5 << " is a " << "number" << endl;

I'm not asking anyone to do it. I'm just looking for a way to be able to. But if you can provide the code that would be good as well. Does anyone have any advice? Thanks.

Upvotes: 2

Views: 645

Answers (5)

James McNellis
James McNellis

Reputation: 355099

template <typename T0, typename T1, typename T2>
void print(T0 const& t0, T1 const& t1, T2 const& t2)
{
    std::cout << t0 << t1 << t2 << std::endl;
}

Upvotes: 14

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726709

If you are looking to simplify the specific task of printing three items, you can do it using a #define macro:

#define print(A,B,C) cout << (A) << (B) << (C) << endl

If you prefer a function-call syntax, consider using C-style output instead: printf is a "first-class member" of the C++ standard library, there is no reason to shy away from it when it makes sense in your specific application:

printf("%d %s %s\n", 5, "is a", "number");

The advantage of printf approach is that it is not limited to any specific number of arguments.

Upvotes: 2

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

I would like to be able to make a function that can take just three arguments

Are you sure? C++11 affords us much more power than that.

void print()
{
    std::cout << std::endl;
}

template<typename T, typename... Args>
void print(const T & val, Args&&... args)
{
    std::cout << val;
    print(args...);
}

Upvotes: 5

Misch
Misch

Reputation: 10840

you could use macros... (if you want to do that, can be ugly sometimes)

#define PRINT(x,y,z) cout << (x) << (y) << (z) << endl;

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258618

You can do it with templates:

template<typename T, typename S, typename U>
print(T x, S y, U z)
{
    std::cout << x << y << z;
}

EDIT: If you're expecting to pass complex types (not just int or char *) you should follow James' answer and use const references.

Upvotes: 4

Related Questions