Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto and static_casts - good practice

In the Scott Meyer's book Effective Modern C++ we can read, that:

std::vector<bool> features(const Widget& w);
Widget w;
…
bool highPriority = features(w)[5];
…
processWidget(w, highPriority); 

and an option with auto

auto highPriority = features(w)[5];

which causes undefined behavior, because of the fact, that features() is returning std::vector<bool>, that uses proxy Object of type std::vector<bool>::reference when returning a value from opearator[].

As a solution to this is adviced not to stop using auto, but using static_casts.

So Scott Meyers advice to use:

auto highPriority = static_cast<bool>(features(w)[5]);

instead of:

bool highPriority = features(w)[5];

My question is: What is a real difference between those two? In my opinion both are the same, because both methods make refactoring harder in exactly the same way (changing return value type in the function features does not make variable highPriority a different type) and second one is shorter to write.

like image 378
DawidPi Avatar asked Oct 08 '15 10:10

DawidPi


1 Answers

If you don't like the interface of features, you can hide the ugliness in a helper function

bool is_high_priority(const Widget& w)
{ return features(w)[5]; }

and now your

auto highPriority = is_high_priority(w);

works as expected.

like image 167
Bo Persson Avatar answered Sep 26 '22 06:09

Bo Persson