Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print different values with different types depending on some condition with operator<<?

Tags:

c++

Let's say I want to print the number args if they are > 1 or "none" if they are <= 1. The only way I know how to do this is:

cout << "number of args: ";
if (argc > 1)
  cout << argc - 1;
else
  cout << "none";
cout << endl;

But then I can't chain the << operator. Ideally, I would like to be able to do something like:

cout << "number of args: "
     << argc > 1 ? argc - 1 : "none"
     << endl;

But this isn't possible because the types from a ternary if are different.

Ideas?

like image 856
mmtauqir Avatar asked Dec 07 '22 00:12

mmtauqir


1 Answers

The simple way. Handle with a string.

std::cout << "number of args: "
          << (argc > 1 ? std::to_string(argc - 1) : "none")
          << std::endl;

It has some superfluous cost to change the string. But it is easy to read and maintain if it is used once. And the reason the parentheses are required is that the shift operator(<<) has higher precedence than ternary conditional operator(?:) or relational operators (>).

like image 124
Chan Lee Avatar answered May 15 '23 01:05

Chan Lee