Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value in ternary operator

Tags:

When using std::weak_ptr, it is best practice to access the corresponding std::shared_ptr with the lock() method, as so:

std::weak_ptr<std::string> w;
std::shared_ptr<std::string> s = std::make_shared<std::string>("test");

w = s;

if (auto p = w.lock())
   std::cout << *p << "\n";
else
   std::cout << "Empty";

If I wanted to use the ternary operator to short hand this, it would seem that this:

std::cout << (auto p = w.lock()) ? *p : "Empty";

would be valid code, but this does not compile.

Is it possible to use this approach with the ternary operator?

like image 389
Hufh294 Avatar asked Oct 01 '21 22:10

Hufh294


2 Answers

auto p = w.lock() is not an assignment. It's a declaration of a variable. You can declare a variable in the condition of an if statement, but you cannot declare variables within a conditional expression.

You can write:

auto p = w.lock();
std::cout << (
    p ? *p
      : "Empty"
);
like image 163
eerorika Avatar answered Sep 28 '22 20:09

eerorika


If you want to introduce a variable for an expression (like let in Lisp or Haskell), you can use a lambda:

std::cout << [p = w.lock()] {return p ? *p : "Empty";}();

This also confines the ?:, which interprets std::cout as part of the condition in your question.

like image 37
Davis Herring Avatar answered Sep 28 '22 20:09

Davis Herring