-->

System.out.println function syntax in C++

2019-06-24 04:01发布

问题:

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

回答1:

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.



回答2:

Many are downvoting, but that's not going to explain why what you're asking is incorrect.

You have two choices here:

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

  2. 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 a const char* and an int. 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 a std::string and a class called Foo, the compiler will look for an operator+ overload which can concatenate those two things.

    Your second option, but slightly more dangerous, is to have a println function that either takes a std::string or const 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.



标签: java c++ println