[CPP] Operator Overloading and templates

We have covered basic operator overloading in the previous blog, to summarize it, operator overloading can:
  • Can define/change meaning of an operator,
  • you can make it as member functions
  • you can use it by a-b, or converts it to a.operator-(b) or operator-(a,b),
  • Access rights like any other function, e.g. has to be a friend or member to access private/protected member data/functions,
  • Also, parameter types can differ from each other, e.g.
  • MyFlt operator-(const MyFlt &, int); would allow an int to be subtracted from a MyFlt.

Continued-Assignment vs comparison

For example, we have created one class. And we new two object of this class, then we want to compare if two object are the same. We can’t simply use ob1 == ob2. Because there is no == operator defined by default. Pointers could be compared though, but not the objects themselves.
That why we need == operator overloading.
enter image description here

Questions to ask yourself

  • Define as a member or as a global? If global then does it need to be a friend?
  • What should the parameter types be? References?Make them const if you can
  • What should the return type be? Should it return *this? Does it need to return a copy of the object?
  • Should the function be const?

Streams use operator overloading

cin, cout and cerr are objects:
  • extern istream cin;
  • extern ostream cout;
  • extern ostream cerr;
  • >> is implemented for the istream class for each type of value on the left-hand side of the operator.
  • The stream object is returned as return value, to allow chaining together.

Templates

Recall #define and macros

  • #define is a semi-intelligent ‘find and replace’ facility
  • Often considered bad in C++ code(Useful in C)
  • const is used more often, especially for members.
  • Template functions are better than macros.
  • #define max(a,b) (((a)>(b)) ? (a):(b))
  • Do you still remember the surprising part about #define
    enter image description here
enter image description here
Therefore, don’t use a macro where the evaluation of the parameters may have a side-effect, that’s why we need template.

Template functions

According to function overloading, we may have multiple versions of the same function, like int, double, char…
But it would be nice to create just the one.(It is like generic in Java)

What templates do

The compiler will actually generate the functions which are needed, according to the parameter, at compile time, new functions are created.

How to create template functions

The easy way to create these template functions:
  • First manually generate a function for specific types
  • Next replace all copies of the types by an identifier
  • Then add the keyword template at the beginning and put the types in the <> with keyword typename(or class)

评论

此博客中的热门博文

[MLE] Linear Classification

[AIM] MetaHeuristics

[CS231] Neural Networks