[CPP] Template classes and functors

Template classes

In the last blog, we introduce template functions:
enter image description here
Also, we can make a template class, which is similar to generic class in Java.
enter image description here

  • Here is a simple version of linked list to store integer value
  • Let’s now using template to make it to store all kinds of data
  • Add prior to each member function definition: template < typename T>
  • Add the < T >to the end of the class name in the member function implementation/definition(if we have separate .h and .cpp file)
  • enter image description here
  • Still remember we use it in STL containers: vector<int> vector1;

Functors

Simple functors

functors are classes which overload () operator
enter image description here

Functors with member data

enter image description here

Functors taking variables by reference

enter image description here

Functors vs Functions

enter image description here
Here, what we did is to use a function pointer and apply function using this function pointer.
But now i want to make the function pointer to functors or make it to use both, what should i do?

  • Use Template!
    enter image description here

What we do here?!
Because function pointer and functor both use () operator, so it will work on both. Also, template is really nice and brilliant on this!
Also, functors are object, they behave like function but it is not a function! The most important thing about them is that they can store things in themselves

Another advanced way

  • < functional> header file
  • std::function< return type (param types) > function name
  • Template class, type specifies return type and parameters
  • Store, copy or invoke any callable of correct type, for example function pointer and functors
  • Useful if you need to store these things for calling later
  • enter image description here

评论

此博客中的热门博文

[MLE] Linear Classification

[AIM] MetaHeuristics

[CS231] Neural Networks