Re: Useful applications for boolean increments?
Am 10/21/12 10:52 PM, schrieb Daniel Kr?gler:
I would like to know whether there are C++ projects or maybe use-cases
out in the wild that have been found useful applications for the
existing language support of pre- and post-increment on bool values,
such as in:
bool pre_inc(bool v) { return ++v; }
bool post_inc(bool v) { return v++; }
Currently, this support is deprecated and the C++ committee is
considering to remove it completely.
If anyone feels that this removal would break relevant code or idioms,
please respond to this query. Short code examples would be very much
appreciated. If that is not possible, but you can point to projects,
it would be helpful to get links to such projects.
I can only imagine one reason why someone would want to use operator++
on a bool variable, which would be that he wants to negate the value in
a single line:
bool negate (bool value) {
return ++value;
}
Such negation could be used like this:
void OnSomeCheckboxClicked () {
if (++checkboxState) {
doSomeChecks ();
}
}
instead of
void OnSomeCheckboxClicked () {
checkboxState = !checkboxState;
if (checkboxState) {
doSomeChecks ();
}
}
Apparently operator++ does not work like this (it seems to invoke
operator++ on the internal representation of a bool):
#include <iostream>
int main () {
bool foo = false;
std::cout << "\n" << foo;
foo++;
std::cout << "\n" << foo;
foo++;
std::cout << "\n" << foo;
}
prints
0
1
1
The only use case for operator++ on bool I could think of was the following:
#include <iostream>
#include <vector>
void print(const std::vector<int>& vec) {
bool needComma = false;
for (auto it = vec.begin(); it != vec.end(); ++it) {
if (needComma++)
std::cout << ", ";
std::cout << *it;
}
}
int main () {
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
print(v);
}
Admittedly, this is a bit far-fetched will probably yield wrong results
for large vectors if bool is implemented using 8bit values.
Regards,
Stuart
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]