C++ class operator overloading - c++

It's possible to overload the not operator for a class:
class TestA
{
public:
bool Test;
const bool operator!(){return !Test;}
};
So that...
TestA A; A.Test = false;
if(!TestA){ //etc }
...can work. However, how does the following work?
if(TestA) //Does this have to be overloaded too, or is it the not operator inverted?
I will add, having read it, I am slightly confused by the typedef solution that is employed, and I don't fully understand what is occurring, as it seems somewhat obsfucated. Could someone break it down into an understandable format for me?

You could write an operator bool(). This takes care of coercion to bool, making statements as your above one possible.

You overload operator void* (like the standard library's iostreams) or use boost's trick of using an "unspecified_bool_type" typedef (safe bool). It does NOT automatically invert your operator!

Related

Overloading parentheses operator on vector in c++

I've tried reading several of the overloading questions here to get an idea how to do that, but as I understand overloading parentheses is different from other operators as it needs to be overloaded inside the class?
I have one file in my project, main.cpp, and I'm trying to overload the () operator as follows:
class vector<int> {
public:
bool operator((iterator a);
};
With a matching function.
bool vector<int>::operator()(vector<int>::iterator a) {
return (*a > 0);
}
But I get several errors, the first one being:
an explicit specialization must be preceded by 'template <>' class
vector {
I've tried to correct what the errors ask for, but it seems my understanding of the process is just not good enough.
What would be the correct method of overloading the operator here?
Thanks in advance for any replies.
You have read right: operator() is one of the four operators (along with =, [] and ->) that can only be implemented as class members. And since std::vector is not yours (be it te template itself or any class specialized from it), you cannot implement them for it.
There is still a solution though, and that is to wrap std::vector inside a class of your own, and overload operator() for that:
struct callableIntVector : std::vector<int> {
using std::vector<int>::vector;
bool operator ()(std::vector<int>::iterator a) const {
return *a > 0;
}
};
The usual caveats about inheriting from standard containers apply: don't destruct them polymorphically as they have no virtual destructor, take care not to slice them, etc.

Metaprogramming C/C++: how can I avoid using macros here?

I am writing a CheckedPtr class to practice exception handling (Stroustrup, TC++PL Exercises, 4th Ed., problem 14.1). I want to overload a bunch of operators, and the code to do this is almost the same. I am using macros to avoid being too repetitive, but I know macros are dangerous, so I was wondering if a better method exists.
Here is my code -- the portion shown is part of what I defined within a class called CheckedPtr. Can I do it better, and/or without macros? I would rather not write all of these functions manually, even if it means some risk with macros.
// This is relatively dangerous.
#define CHECKED_PTR_OVERLOAD_COMPARATOR(OP) \
template<typename Ptr> \
bool operator OP(Ptr& p) { return pos OP &*p; }
CHECKED_PTR_OVERLOAD_COMPARATOR(==)
CHECKED_PTR_OVERLOAD_COMPARATOR(<)
CHECKED_PTR_OVERLOAD_COMPARATOR(>)
CHECKED_PTR_OVERLOAD_COMPARATOR(<=)
CHECKED_PTR_OVERLOAD_COMPARATOR(>=)
#undef CHECKED_PTR_OVERLOAD_COMPARATOR
As the commenters have already said, do not use macros for this. If you want to have a minimal implementation but a complete set comparison functions, I believe Boost.Operators is your best bet. The example shown on the page I linked to is:
struct animal : public boost::less_than_comparable<animal>
{
std::string name;
int legs;
animal(std::string n, int l) : name{std::move(n)}, legs{l} {}
bool operator<(const animal &a) const { return legs < a.legs; }
};
where implementing the single operator< function and having the animal class derive from boost::less_than_comparable<animal> gives you the operators >, <=, and >=.
There are other questions on stackoverflow that are related. See
how to use std::rel_ops to supply comparison operators automatically?
How do boost operators work?

When an object provides both `operator!` and `operator bool`, which is used in the expression `!obj`?

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).

Overloading operator `:=` in C++

Why I can't create or overload operator := in my class in C++?
Is there are some list operators that I can overload?
I can only overload, or also create some new custom operators?
Because no such operator exists in C++. You cannot roll your own operators because you would need to modify the grammar of the language for the parser to recognize them.
You can find a list of the available operators here or here (or better yet by reading the standard if you can get a copy).
Finally, be advised that overloading operators like there is no tomorrow is a mistake that pretty much every C++ beginner makes; operators are really nothing more than functions, and unless there is a very good case to be made for overloading an operator most of the time it's a better idea to just write a plain function for your class instead. For example, std::string does not have an operator* even though it could be argued that it's convenient to write
string sleepy = string("z") * 40;
The operators you can overload are:
Perhaps you meant the assignment or the equals operator.
class Object{
public:
///Overload The Assignment Operator
Object& operator=(const Object& objectIn);
///Overload The Equals Operator
bool operator == (const Object & rhs) const;
protected:
private:
};

How can I return a value from a class object?

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() { /* ... */ }