I want to create a function in C++ using cout that has the same as the println function in java. This means that the call should be something like this:
int a=5
println("A string" + a);
the variable a should have any basic type. What kind of parameter should I have in this case and how would it work?
Thanks
Many are downvoting, but that's not going to explain why what you're asking is incorrect.
You have two choices here:
You can make a templated
println(T val)
function which takes any type you like, ints, doubles, etc, and you can print them in that function.However, what you're requesting up there:
"A string" + a
this is an expression which will return a type. What you're doing here is adding aconst char*
and anint
. This unfortunately isn't going to do anything like what you expect, it's going to do pointer arithmetic, and in this particular case won't even compile. But for the general case, say astd::string
and a class calledFoo
, the compiler will look for anoperator+
overload which can concatenate those two things.Your second option, but slightly more dangerous, is to have a
println
function that either takes astd::string
orconst char*
and to define all the different operator+ operations that you might want. I don't recommend this though, as the default operation between a pointer and an integer is to do pointer arithmetic, which is very useful.I recommend starting with a template function, and seeing what happens from there.
As larsmans already pointed out, java has overloads on the operator +. So you can concat strings with integer. This is also possible in C++ but not out of the box for all types.
You could use a templated functions like this.
But I would recommend to take a look at boost::format. I guess this library will do what you want.