C++ assign a logical operator function to a variable - c++

I am trying to assign a logical operator function to a variable but am unable to get it to work. I am using:
function<bool(double,double)> opFunct = less<bool>();
double highorlow = pOut.high;
if(pCheck){
opFunct = greater<bool>();
highorlow = pOut.low;
}
if(opFunct(highorlow,pStay.middle){
//never gets done
}
The problem with this code is no matter what the highorlow,pStay.middle doubles are, it returns false.
What am I missing?
Thanks

Short version:
less<bool> compares bools. Use less<double> to compare doubles (also in greater<>).
Long version:
This is an interesting question. Specifically, how come the following line compiles?
function<bool(double, double)> opFunct = less<bool>();
After all std::less<bool>:: operator() looks like bool(bool, bool), why does it match bool(double, double)?
Well that's because the check that std::function's constructor performs is simply whether less<bool>() can be invoked as bool(double, double), and yes it can! double is implicitly-convertible to bool, 0.0 becomes false and any other value true.
That obviously won't produce the expected result because e.g. opFunct(1.0, 2.0) will invoke less(true, true) which will return false.
The fix is to change bool to double
function<bool(double, double)> opFunct = less<double>();
And also here
opFunct = greater<double>();
But wait, std::function overhead aside1, depending on how the rest of your code looks like, the fragment shown can potentially be simplified to just:
if (pCheck ? pStay.middle < pOut.low : pOut.high < pStay.middle) {
// . . .
}
Or maybe even
if (pStay.middle < pOut.low || pOut.high < pStay.middle) {
// both checks at once . . .
}
1std::function comes at a cost of some 48-96 bytes of memory and an extra indirection or two. Compare the generated code for version with std::function vs. version without std::function.

Related

Cast AlignedBox double to AlignedBox int

I'm trying to use Eigen AlignedBox. Specifically, I'm trying to cast a box of double into an int one, by using AlignedBox::cast
AlignedBox<double, 2> aabbox2d = AlignedBox<double, 2>(Vector2d(0.52342, 2.12315), Vector2d(3.87346, 4.72525));
aabbox2d.cast<AlignedBox<int, 2>>();
auto minx = aabbox2d.min().x();
Anyway, when the execution gets to min() I get an assert:
Assertion failed: (((SizeAtCompileTime == Dynamic && (MaxSizeAtCompileTime==Dynamic || size<=MaxSizeAtCompileTime)) || SizeAtCompileTime == size) && size>=0), function resize, file /Users/max/Developer/Stage/Workspace/AutoTools3D/dep/libigl/external/eigen/Eigen/src/Core/PlainObjectBase.h, line 312.
Note that this is different from casting a matrix scalar to another one. An object is implied.
Supposedly I'm not doing the cast correctly. Does someone know the right way?
Thank you
Consulting the documentation for AlignedBox::cast shows that the template argument to cast is defined as template<typename NewScalarType> and the return value is *this with scalar type casted to NewScalarType. Thus the cast function does not modify the existing instance of the box, but returns a new one. To make your example work you need to store the returned instance like follows:
AlignedBox<double, 2> aabbox2d = AlignedBox<double, 2>(Vector2d(0.52342, 2.12315), Vector2d(3.87346, 4.72525));
AlignedBox<int, 2> casted = aabbox2d.cast<int>();
const int minx = casted.min().x();
You can play with this here: https://godbolt.org/z/ozE4rzebb
As a side note: as the documentation states, when working with Eigen one should refrain from using auto (probably not a problem in this case though)

ADTs and values

In Rascal, say I have the code:
value x = 2;
data Exp = con(int n);
Is there a way to call con(x), while x is a value (but actually an integer), without knowing on beforehand what the type of con's first argument is supposed to be (thus without explicitly casting it to an int)?
Why is it possible to call a function, say int something(int n) = n, with an integer defined as a value (e.g. value y = 2) passed into its first argument, while it gives me an error when I try to do the same with user-defined ADTs?
When you call a function in Rascal it actually is doing a pattern match on the arguments. So, if you define int something(int n) = n;, and then call something(x), it matches x with int n, sees that x is actually an int (so it can bind the value to n), and calls the function.
If you were to define value x = 2.5 instead and then call something(x) you would get an error since it cannot bind the value 2.5 to int n. You could overload something with a second definition that takes a real instead, like int something(real r) = toInt(r);, and it would then work. Two items to note here, though: something needs to return the same type in both cases, and you need to import util::Math to get access to toInt.
When you are using a constructor, like con(x), it doesn't do a pattern match for you automatically. The type that you give it has to match the type it expects. If you know that x will always be an int, it would be best to just declare it as such. Another option would be to create a function like Exp makeCon(int n) = con(n); which you could then use as you would like, i.e., Exp myExp = makeCon(x);. It would be best in this case to include a default version of the function, just in case you give it something unexpected, like default Exp makeCon(value x) { throw "Unexpected value <x>"; }, this way if you ever try to create a con with something that isn't an int you will get an error that you can handle, with the ability to create your own error message, add additional error handling versus just showing a message, see the value causing the problem, etc, versus just having the interpreter give an error (which may not give you all the info you want).

When returning a boolean, why use "!!"

I saw some C++ code like this:
bool MyProject::boo(...)
{
bool fBar = FALSE;
....
return !!fBar;
}
I couldn't think of any difference between returning fBar directly in this case and returning !!fBar. How two negatives make a difference?
Thank you
In your example, there's no difference between returning fBar and returning !!fBar.
In other cases, e.g. when a user-defined type such as BOOL (typedef-ed to be int) is used, the !! construct has the effect of coercing any non-zero value to true; i.e. !!fBar is equivalent to fBar ? true : false. This can make a difference if fBar can be 5 and you want to compare it against TRUE, which is defined to be (BOOL)1.
This is typically done to avoid compiler warnings in situations when a non-bool value has to be converted to bool type. Some compilers (like MSVC++) issue a "performance" warning when a non-bool value is implicitly converted to bool. One way to suppress this warning is to use an explicit conversion. Another way is to use the !! combination.
However, in your case the argument of return is already declared as a bool, meaning that the above reasoning does not apply. (Are you sure it was bool and not, say, BOOL?). In that case there's no meaningful explanation for that !!.
!! "is" "to boolean" operator (not really, it is two negate operators). It make no different is this case. However, it will make difference if is not bool.
e.g.
int fBar = 2; // !!fBat evaluate to 1
bool b = (fBar == true) // this is false
b = fBar; // this is true
b = !!fBar; // this is also true
typedef int MyBool; // say some library use int as boolean type
#define MY_TRUE 1
#define MY_FALSE 0
MyBool b2 = fBar; // this evaluate to true, but not equal to true
if (b2 == MY_TRUE )
{
// this code will not run, unexpected
}
if (b2)
{
// this code will run
}
MyBool b3 = !!fBar;
if (b2 == MY_TRUE )
{
// this code will run
}
if (b2)
{
// this code will run
}

Ternary expression which "does nothing" (noop) if the condition is false?

Out of curiosity I started wondering if it's possible to have a ternary expression that, if it evaluates to false, does nothing in the false branch.
Ie is there a way to write something like this:
variable = (someBool) ? i : <do nothing>;
As opposed to:
if (someBool) {
variable = i;
}
I tried ((void)0) or while(false){}; as no-op but the compiler expects an expression.
UPDATE:
I realized the question lost some meaning because I tried to make the code easier. The initial idea I had was to initialize a static var with a ternary - using the static var itself as the condition:
static int var = (var != 0) ? var = 1 : (var already initialized, do nothing);
This is assuming that uninitialized variables are initialized to 0 which is not always true (or never in release builds, not quite sure). So maybe it's a hypothetical question.
how about short-circuit?
int variable = 0;
bool cond = true; // or false
(cond && (variable = 42));
printf("%d\n", variable);
How about this:
variable = (someBool) ? i : variable ;
Though I would personally prefer the original if statement
Compilers not only expect expression, but the expression the returns type on the left side (the type of variable whatever is it). So, no you can not do that. It's not conditional execution, but variable member assignment.
These are completely different things.
In second example :
if (someBool) {
variable = i;
}
you do not assign anything, but simply execute based on condition. So in your case, where you don't want to do anything (not assign anything), the way to go is conditional execution so use simply the second case.
The format of the conditional expression is
<expression> ? <expression> : <expression>
In other words, it must have some expression.
Addressing your edit: in C99 variables of static scope are initialised to 0. However, I have never really trusted that because I've been programming in C since the K&R days.
Anyway, just initialise the variable. As the variable is static, it's only going to happen once during the whole execution time of the program.
You could do:
variable = !someBool ?: i;
Since the ?: will no-op when the if expression is true but assign i if it's false.
Note: This has only been tested in Obj-C
How about
(someBool) ? (variable = i) : NULL;
For C# says:
Syntax:
condition ? first_expression : second_expression;
And it says about first_expression and second_expression:
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
If you were to evaluate a nullable object type instead of bool, you could always write:
variable = myVar ?? i;
Hacky/cludgey/impractical - probably all 3, but for the sake of this question it's a way of omitting an 'else'.
Try: null lambda.
auto null_lambda = [](){return;};
int a = 1;
int b = 2;
vector<int> c;
a > c ? b = c.push_back(b) : null_lambda();

Difference between !(variable) and (!variable)

In either C or C++, is there a conclusive difference between using !(variable) and (!variable) in an if-statement, such as:
if (!(variable)) { .. // do something }
or
if (!variable && !(variable2)) { .. // do something }
such that one version delivers a different result over the other?
Its all about order of operation. Using !(variable) will evaluation all conditions inside of the parenthesis then do the ! (or NOT) to determine whether to enter the if statement where-as (!variable will do the NOT specifically on the variable itself.
So in the situations:
!(true && false) = true
!(true && true) = false
(!true && !false) = false
(!true && true) = false
!(true && !false) = false
...and so on
Hope this helped.
The only way it would make a difference is if the variable is an expression, then its a matter of operator precedence. Otherwise && has lower precedence than !
There is no difference between
!(variable)
and
(!variable)
but if you are using operators that has different precedence you will have a difference. For example, if you write
!(varible1 && variable2)
is not the same as
!varible1 && variable2
because the NOT will be applid to the whole operation in the first case and only to varible1 in the second case.
May be you are getting a problem with the evaluation, C has lazy evaluation, so when the execution detects that boolean evaluation has a result, it doesn't try the other values. So, now consider instead of variables you have functions.
int foo() { printf("foo\n"); return 1; }
int bar() { printf("bar\n"); return 0; }
If you write
if (foo() && bar()) { ... }
you will get
foo
bar
but if you write
if (bar() && foo()) { ... }
you will only get
bar
because the evaluation will be false, doesn't matter the result of foo
No, in your example the first one (although the parens are unbalanced :)) behaves exactly like it would if there were no parentheses, and the second behaves the same way. You can even do this
if ((!((((variable)))))) { ... }
But don't :)
They should never evaluate to different things. Parentheses used this way are really for grouping operations, but in this case, you're not grouping any operations, just the expression itself.
So !(x) is just a pedantic way of writing !x
Now, if you had an operation inside the parentheses, that's where the differences start.