C++ Creating A PrintLine Function

时间:2016-04-04 18:28:55

标签: c++

Hello I want to create a function like System.println() in Java , instead of using cout in C++; I want to create like ,

  void println(string text){cout<<text<<endl;}

I wonder how I can make this using generic type paremeter instead of string type , so that I can print integers,doubles as well. Thank you.

2 个答案:

答案 0 :(得分:3)

I wonder how I can make this using generic type paremeter instead of string type ...

Just use a generic parameter (provide a templated function):

template<typename T>
void println(T&& x) { std::cout<< x << std::endl; }

All existing overloads of std::ostream& operator<<(std::ostream&, T&& x) will apply and be deduced correctly.

答案 1 :(得分:0)

I think templated functions could be helpful. Check out this answer from 2 years ago. I used this solution to implement a basic logging feature for my needs.

Hope this helps!