To my understanding,
bool conditional = getTrueOrFalse();
will set conditional to what getTrueOrFalse() was at that exact line in the code.
How can I make it to where every time the variable conditional is used, it will call getTrueOrFalse() (as getTrueOrFalse() switches between true and false at different points throughout the program)? Am I able to set conditional to a different boolean-returning function later on?
You can try function pointers.
#include <functional>
std::function<bool()> conditional = &getTrueOrFalse; // no evaluation yet
if ( conditional() ) // actual evaluation
{
} else {
}
conditional = &isSunShining; // no evaluation yet: just point to something else
The OP isn't clear because you are not thinking about functional evaluation. You must ask yourself, when do I actually want to evaluate the function? When you use the parentheses, you are actually evaluating the function or the function pointer. In your OP example, you have, technically already evaluated the function once and assigned it to the boolean conditional.
If you want an evaluation at a later point in your program, you will have to call the function again, explicitly, or implicitly, through a function pointer like my snippet above.
Also note that the boolean conditional is just a simple memory location with a binary representation of true/false - it has no idea of a refresh my value on read. However, if you use the std::function<> conditional instead (like in my snippet), you can re-evaluate it every time you use the parenthesis operator.
Just for reference, there are many other ways to accomplish essentially the same feat:
lhs = left-hand side or where you store the address
rhs = implementation of your operation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With