简体   繁体   中英

C++ - Cast char reference to bool referenece (std::vector<bool>)

I have a problem casting a char reference to a bool reference. I have a simple GUI library that has the following method gui->addButton(string name, bool& value); . If the button is clicked the bool is flipped. Now I want to have a dynamic/unknown amout of buttons. Hence I though I could create a vector of bools, simply push_back a new bool for every button created and give the addButton method a reference to the last vector element. Something like this:

bool isOnFlag = true;
buttonFlagVector.push_back(isOnFlag);
gui->addButton(name, buttonFlagVector.back());

Sadly because of the specialization of vector for bools , that doesn't work.

From what I read the common way to avoid the specialization for bool is to use a std::vector<char> . I tried that and the problem I am having is that I don't know how to cast from a char reference to a bool reference. dynamic_cast reinterpret_cast ? None of them seem to work.

Can somebody point me in the right direction? Thanks in advance!

Unfortunately the size of a bool is implementation defined and may differ on different compilers. So even though a reinterpret_cast could work, I would recommend against it. Instead you could use a small wrapper struct like this:

struct SpecialBool { bool b; };
std::vector<SpecialBool> bools;

Unfortunately you also have another problem with your approach in that you cant store references to elements in a std::vector while you are still adding elements to it. On each push_back the internal memory may be reallocated which will invalidate all your previous references.

You can wrap your bool in your struct to avoid std::vector<bool> specialization:

struct buttonState
{
    bool checked;
};

std::vector<buttonState> buttonStates;

And latter:

bool isOnFlag = true;
buttonFlagVector.push_back({isOnFlag});
gui->addButton(name, buttonFlagVector.back().checked);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM