简体   繁体   English

C ++-将字符引用转换为bool Referenece(std :: vector <bool> )

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

I have a problem casting a char reference to a bool reference. 我在将char引用转换为bool引用时遇到问题。 I have a simple GUI library that has the following method gui->addButton(string name, bool& value); 我有一个简单的GUI库,它具有以下方法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. 因此,尽管我可以创建一个布尔向量,但只需为创建的每个按钮push_back一个新的布尔值,并为addButton方法提供对最后一个向量元素的引用。 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. 遗憾的是,由于bool的vector专门化 ,因此无法正常工作。

From what I read the common way to avoid the specialization for bool is to use a std::vector<char> . 据我了解,避免对bool进行专业化的常见方法是使用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. 我试过了,我遇到的问题是我不知道如何从char引用转换为bool引用。 dynamic_cast reinterpret_cast ? 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. 不幸的是, bool的大小是由实现定义的,并且在不同的编译器上可能有所不同。 So even though a reinterpret_cast could work, I would recommend against it. 因此,即使reinterpret_cast可以工作,我还是建议不要这样做。 Instead you could use a small wrapper struct like this: 相反,您可以使用一个小的包装器struct如下所示:

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. 不幸的是,您的方法还有另一个问题,就是当您仍向其中添加元素时,无法将对元素的引用存储在std::vector On each push_back the internal memory may be reallocated which will invalidate all your previous references. 在每个push_back ,都可能会重新分配内部存储器,这将使您之前的所有引用无效。

You can wrap your bool in your struct to avoid std::vector<bool> specialization: 您可以将bool包装在struct以避免std::vector<bool>

struct buttonState
{
    bool checked;
};

std::vector<buttonState> buttonStates;

And latter: 后者:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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