1

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.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
ccca
  • 75
  • 2
  • 11

2 Answers2

4

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
  • 13
  • 116
  • 190
  • My first reaction is that this should use an rvalue reference instead of an lvalue reference. With an lvalue reference, something like `println(2)` requires creating a temporary object initialized from the value, then binding the reference to that temp, rather than binding directly to the rvalue (i.e., what you're doing is forwarding the parameter, leading to all the arguments favoring rvalue references to get perfect forwarding). Probably irrelevant to the OP though... – Jerry Coffin Apr 04 '16 at 18:49
  • I agree with jerry Coffin. If you replace the parameter with `T && x`, your function will be able to accept *both* lvalue and rvalue references, which is useful. – HolyBlackCat Apr 04 '16 at 18:51
  • @HolyBlackCat Ah, I see my mistake. – πάντα ῥεῖ Apr 04 '16 at 18:52
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!

Community
  • 1
  • 1
Anup Puri
  • 65
  • 6