Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.out.println function syntax in C++

Tags:

java

c++

println

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

like image 301
Hanelore Ianoseck Avatar asked Apr 18 '13 13:04

Hanelore Ianoseck


1 Answers

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.

#include <iostream>
using namespace std;

template <typename T>
void printer(T t) 
{ 
    cout << t << endl;
}

template <typename T, typename ...U>
void printer(T t, U ...u)
{
  cout << t;
  printer(u...);
}


int main()
{
  int a=5;
  printer("A string ", a);
  return 0;
}

But I would recommend to take a look at boost::format. I guess this library will do what you want.

like image 153
mkaes Avatar answered Sep 20 '22 20:09

mkaes