I'm trying to implement my own boolean class, but cannot replicate native semantics for &&. The following contrived code demonstrates the issue:
#include <iostream>>
class MyBool {
public:
bool theValue;
MyBool() {}
MyBool(bool aBool) {theValue = aBool;}
MyBool operator&& (MyBool aBool) {return theValue && aBool.theValue;}
};
bool f1() {std::cout << " First\n"; return false;}
bool f2() {std::cout << " Second\n"; return false;}
int main(int argc, char** argv) {
std::cout << "Native &&\n";
f1() && f2();
std::cout << "Overloaded &&\n";
MyBool(f1()) && MyBool(f2());
return 0;
}
When compiled and run, the result is:
Native &&
First
Overloaded &&
Second
First
In other words, && on bools is lazy (as any C++ programmer would expect) but the overloaded && isn't (as this C++ programmer at least didn't expect).
Is there a way to make overloaded && lazy? I can find various full-on lazy evaluation schemes to provide Haskell-like functionality, but they seem like complete overkill for my use case.
You should not overload bool operator&&, since you lose short circuit evaluation, as you have discovered.
The correct approach would be to give your class a bool conversion operator
class MyBool {
public:
bool theValue;
MyBool() {}
MyBool(bool aBool) : theValue(aBool) {}
explicit operator bool() { return theValue; }
};
Note that explicit conversion operators require C++11 compliance. If you do not have this, have a look at the safe bool idiom.
Is there a way to make overloaded && lazy?
No.
You can make almost anything evaluate lazily with the expression template idiom, including but not limited to the operators whose built-in versions short-circuit. But that's more work than you need for this one case, since then your MyBool class would require a lot more code.
If you really want short-circuiting and are willing to sacrifice the operator syntax, you can rename your operator&& method to _and, define an AND() macro, and write AND(x,y) instead of x&&y.
#define AND(x,y) (x._and(x.theValue ? y : MyBool(false)))
With some macro hacks you can have AND() accept a variable number of parameters.
The _and() method here is not intended to be used "publicly" here but must be declared public since you can't friend a macro.
For something as simple as your MyBool class, this is probably unnecessary. But if you need your operator&& to have special side-effects like updating some state on this, then this gets the job done.
Related
I've ran across a question I am not able to answer for myself. Also, I didn't find an answer to this on both google and here. Say, I want to "check an object for validity" in an if clause, like so:
MyClass myObject;
// [some code, if any]
if (!myObject)
{
// [do something]
}
Let MyClass be defined something like this:
class MyClass
{
public:
MyClass() { };
virtual ~MyClass() { };
bool operator!()
{
return !myBool;
};
operator bool()
{
return myBool;
};
private:
bool myBool = 0;
};
My question now is: Which one of the overloaded operators is actually used in this if clause? Either way, the result is obviously the same.
It will use operator!.
A function whose parameter types match the arguments will be chosen in preference to one that requires type conversions.
You'll find that operator ! gets executed because it's the most direct resolution. If it used operator bool instead then it would have to call the conversion operator first, and then apply the ! separately to that.
As a general rule, it's a good idea to avoid that situation though. It's generally better just to define the bool conversion, because strictly speaking that's what you want your logical operators to act on, rather than MyClass directly. Defining both creates a bit of a readability problem, and is a form of redundant code duplication (which can lead to programmer error in future).
I have the following code:
class A
{
public:
A() {};
void operator[](int x)
{
}
};
int _tmain(int argc, _TCHAR* argv[])
{
A a;
a.operator[](0);
a[0];
}
Both calls work, but I want to know whether there is any difference. Is one more efficient than the other? Do other things happen(besides executing the code in the overloaded operator) in either case?
EDIT:
Is there a case why you would want to write a.operator instead of just []. What's the point of overloading if you're not using the short syntax?
Both calls are identical. All the operators can be called with an explicit .operator## syntax, where ## stands for the actual operator symbol.
It is the literal operators like a + b that are just syntactic sugar for a.operator+(b) when it comes to classes. (Though of course for primitive types that is not the case.)
Note that your []-operator is not very typical, since it is usually used to return a reference to something -- but it's up to you how to implement it. You're restricted to one single argument, though, unlike operator().
The explicit operator[] (and any other explicit operator) is used in an inheritence heirarchy, where you are trying to call operator[] on a base class. You can't do that using the normal [], as it would result in a recursive function call. ie; you might use something like this:
struct Base {
void operator[] (int i) { }
};
struct Derived : public Base {
void operator[] (int i)
{ Base::operator[](i); }
};
Other than having to type another 11 characters, there is no functional difference between the two.
They are completely equivalent - just in once case C++ adds syntactic sugar that makes your code prettier. You can call all overloaded operators explicitly - the effect will be the same as when they are called implicitly and the compiler redirects calls to them.
No there is no difference between both versions from performance point of view. a[0] is more readable.
Also, the operator [] is typically defined as,
Type& operator[](const int x)
{
return v[x]; // Type 'v' is member variable which you are accessing for array
}
I was told that you can in fact do MyClass a, b; ... if (a && b) {...} without 1) overloading the && operator 2) overloading the bool operator (ex: class MyClass { ... operator bool(){return boolval; } };)
The solution was to use a pointer-to-member-function. I did not understand how to use this solution. My notes say the below but i couldn't get more then that. Does anyone know how to do this?
the function takes a private nested
struct as a parameter. The reason is
that that type can’t legally be
converted into anything else – it can
never be used in any expression other
than a Boolean context
Note: Typically answers to [homework] questions do not immediately give away the solution. However, according to your question you already know the solution but don't understand it. I'll attempt to explain.
From the information you provided in your question, your instructor was probably talking about some variant of the safe bool idiom:
class MyClass
{
private:
typedef void (MyClass::*SafeBoolType)() const;
void ThisTypeDoesNotSupportComparisons() const {}
public:
operator SafeBoolType() const {
// The actual conditional expression would go where "true" is.
// ____
// | |
return (true) ? &MyClass::ThisTypeDoesNotSupportComparisons : 0;
}
};
int main()
{
MyClass a;
MyClass b;
if(a && b) {} // Compiles.
/* if(a < b) {} */ // Doesn't compile.
}
Here, we provide a type cast operator to a pointer-to-member-function, which can only be used in boolean contexts. This allows the if statement with the logical operator (&&) to compile even without a bool typecast or an && operator overload. It also prevents the if statement with the comparison operator (<) from compiling.
However, I don't understand the part in your notes that mentions "the function takes a private nested struct as a parameter". The safe bool idiom doesn't require that the member function take an unnamed struct. I suggest that you ask your instructor; it is possible that I have completely misunderstood the problem.
Is it possible to have a class object return a true/false value, so I can do something like this:
MyClass a;
...
if (a)
do_something();
I can accomplish (almost) what I want by overloading the ! operator:
class MyClass {
...
bool operator!() const { return !some_condition; };
...
}
main()
MyClass a;
...
if (!a)
do_something_different();
but I haven't found a way to overload what would be the "empty" operator. Of course, using the == operator to check for true/false is also possible, and is in fact what I have been doing so far.
Overload the void * cast operator:
operator void * () const { return some_condition; };
this is how streams work, allowing you to say:
if ( cin ) {
// stream is OK
}
The use of void * rather than bool prevents the cast being used by mistake in some contexts, such as arithmetic, where it would not be desirable. Unless, you want to use it in those contexts, of course.
The obvious solution – providing an implicit conversion to bool via operator bool – is a bad idea.
That’s why the standard library uses operator void* as shown in Neil’s answer.
However, it’s worth pointing out that even this solution has flaws and is therefore no longer considered safe. Unfortunately, coming up with a better solution isn’t trivial …
There’s an article over at Artima that describes the safe bool idiom. For a real library, this is definitely the way to go, since it offers the most robust interface that is hardest to use wrong.
Weird, no one has mentioned the safe bool idiom so far. All the other solutions described so far have drawbacks (which you might or might not care about), all those approaches are described in the article. In a nutshell, the safe bool idiom goes something like this:
class Testable {
typedef void (Testable::*bool_type)() const;
void this_type_does_not_support_comparisons() const {}
public:
operator bool_type() const {
return /* condition here */ ?
&Testable::this_type_does_not_support_comparisons // true value
: 0; // false value
}
};
Try overloading the (bool) operator:
operator bool() { /* ... */ }
I'm looking to add functionality to all the simple types in C++.
I want to write a single templated class that takes as a template parameter the type to be encapsulated and then has all the operators defined so that the encapsulated class works exactly as the simple type it encapsulates.
Something like this:
template <typename _SimpleType_>
class Attribute
{
public:
Attribute(_SimpleType_ value){ m_value = value; }
~Attribute(){}
// Cast
operator _SimpleType_() { return(m_value); }
// Comparisons
bool operator==(const a& other) const { return a == m_value; }
etc...
private:
_SimpleType_ m_value;
}
// Use like:
Attribute<int> i = 20;
while(i)
{
if((i & 0xF) == 0)
{
i >>= 2;
}
i--;
} etc...
The question is I'm sure there are a load of nuances that have to be dealt with and specialised template operators written; so is there anywhere that this has already been done so that I can just use that instead?
Boost is too large and complicated to put in my project but I can look at it for pointers if there is a class like this in there - whats its name if there is?
It's pretty simple, if tedious, - you just have to implement all the operators supported by the standard types and where the cast operator is not sufficient.
I have to ask though, why on earth are you trying to do this?
Here is an example of doing with an automatic typecast to T& (tested with GNU C++ 4.3.2):
#include <iostream>
using namespace std;
template <typename T>
class Attribute {
public:
Attribute(const T &value) { v = value; }
operator T & () { return v; }
private:
T v;
};
int main(int argc, char **argv)
{
Attribute<int> i(0);
i = 3;
i++;
i += 4;
i = i + 5;
i <<= 3;
cout << "i is now " << i << endl;
}
The C++ compiler casts automagically the reference to 'Attribute' to a reference to 'int' using the coercion operator 'operator T & ()'. So when the Attribute class does not provide the '++' operator or anything, the object is typecasted to int & and then the operator is looked up from there. Feel free to experiment.
You can get the implementation of the nonmutating operators for free, just by the conversion to _Simple_type_ (and you would get the assignments and increment/decrement by conversion to _Simple_type_&). Another question is whether this is really a good idea, as it creates conversions both T to Attribute<T> and Attribute<T> to T which causes problems while overloading - but you could fix that by making the constructor of Attribute<T> explicit.
This leaves the assignments and increment/decrement - you would just have to implement those.
Another possibility is using boost::operators - a header only library that facilitates creation of operator overloads based on algebraic rules. eg. you create operator+=, and it will provide you operator+. You create operator< and operator== and it will give you the other relationals etc.
Not to do with your question, but you should be aware that names such as _SimpleType_ (that is, names that begin with an underscore and an uppercase character) are reserved for the C++ compiler and Standard Libarary implementors to use - you are not allowed to use them in your own code.
I'm not sure if boost::ref is what you're looking for.
At any rate, the best thing you'd do is to just write it out by hand -- but this will start becoming a problem if you intend to support pointer and reference semantics.
What you'd also proabably need to do is put it in a namespace and implement the free function operator overloads and rely on ADL for it to get picked up. This will get a little unwieldy though as you implement more and more operators.
I like this form of encapsulation of simple types (original author - Sektor van Skijlen):
template<typename T>
class explicit_t
{
private:
T value;
template<typename V> explicit_t(V t);
public:
operator T&() {return value;}
explicit_t(const T& c) : value(c) {}
};
And the short example:
void fun(explicit_t<int> foo) {}
int main()
{
// fun('a');
// fun(3u);
// fun(3.0);
fun(4);
}
So what do I get? No more unwanted conversions.
You might also want to have a look at something more fancy - typegen.