All about programming in GNU/LINUX

Source code

Preparing to land on C++ core of NodeJS: Sharpening the weapons – Using C++ Templates

Ahhhhhhhhhhhhhhh!!!!!! Travelling 700Kms without music or books on Technology is so pissing off!!!!This is what i call as “Throw away your frustration blog”  😛 😛 Enough !!!!
In the last blog i started out the series on Peeking into the Source code of node.Js .And also i promised to get into the C++ core of NodeJs while i had restricted myself to the
top most layer of node , that is the Javascript layer of it , dont remember ?? :PThen take a look at this .
So you might be thinking now “Yaay, its now time to start with the C++ core of NodeJs”….But when i started out with the defination of GetCIphers() of the TLS node module inside the C++ core ,the C++ lines of code written were just mindblowing. If you check the lines between 4807-4823 in this link from source of node you’ll understand C++ sophistication that lies beneath. It was important to get back to few important C++ concepts before landing on the C++ core of Node.So this post is on Preparing to land on NodeJs C++ Core..To be precise get Ready for a glimpse on C++ Templates and meddling around with them .C++ templates are widely used within the NodeJs core , so its vital to understand them thoroughly

Being into Hardcore Javascript development from past 15 months the term “template” reminds me of ReactJs , AngularJs Templates ,Jade , EJS ,Handle bars and Underscore Templates .Like Templates in Javascript libraries are used to generate dynamic html ,templates in C++ are used to write “generic programs ” where in the same piece of code can deal with variety of datatypes .

Still confused ??? Ill illustrate an example Lets say your are building a class which provides all the functionalities of a calculator .
Here is the link for the code on github .You can execute the code with cloud C++ IDE by clicking on this link


#include <iostream>
using namespace std;
class calculator {
    public:
		int add(int x,int y);
		int multiply(int x,int y);
	
};  

int calculator::add(int x,int y){
	return x+y;
}

int calculator::multiply(int x,int y){
	return x*y;
}
int main(){
    calculator instance;
    cout<<instance.add(1,2)<<endl;
    cout<<instance.multiply(5,2)<<endl;
}

.
So whats the issue here.
You can clearly see that the member functions Add and Multiply of the class Calculator
can work only on integer datatypes. They return int , the add take int values as
their parameters .
What if this decision on the data type to be worked upon could have made dynamic ??
What if the a same piece of code can dynamically make the same piece of code work for
various datatypes . Yes , its possible by the use of C++ class templates.
By using C++ class templates any given member function can be made flexible enought to be
able to work on various datatypes . Here is how to do it .Here is the implementation using
C++ template classes .
Here is the link of the code on Github.Click here to execute the same code using online C++ editor

template <typename Type> class calcultor{
	public:
		Type multiply(Type x,Type y);
		Type add(Type x,Type y);
}

template <typename Type> Type calc<Type>::add(Type x,Type y)
{
	return x+y;
}

template <typename Type> Type calc<Type>::multiply(Type x,Type y)
{
	return x*y;
}

calcultor <int> instance1;
claculator <double> instance2;

baffled ??? 😛
Here is the detailed explanation ,

template <typename Type> class calculator {}

is the declaration of the template class , here template and typename are the keywords and
this should be followed after the typename keyword , a placeholder name has to be given
to the variable datatypes that is sent during the creation of the object of the template class.
but it has to be made sure that the same placeholder name has to be used to refer to the
datatype in its member function .

Type multiply(Type x,Type y);

by using this declaration the return type and the parameters of the member functions are also
made dynamic and are ot predefined like it is in the first case .

this is the format for writing the defination for the member functions of a template class .

template <typename [namespace]> return_type parent_class<[namespace]>::member_function(parameters);

and Both the parameters and return Type can itself be dynamic template varialbles (as it is the case
the template class code example )

now while creating the new instance of the object you have the freedom to choose and set the
datatype on which the member functions process upon .

calculator <int> instance1; 

Now the ‘Type’ will be set to int , so this is equivaluent to

class calculator {
	public:
		int add(int x,int y);
		int multiply(int x,int y);

}  

int calculator::add(int x,int y){
	return x+y;
}

int calculator::multiply(int x,int y){
	return x*y;
}

now ,

calculator <double> instace2;

this is equivalent to

class calculator {
	public:
		double add(double x,double y);
		double multiply(double x,double y);

}  

double calculator::add(double x,double y){
	return x+y;
}

double calculator::multiply(double x,double y){
	return x*y;
}

The same analogy can be applied to create functions templates .It is illustrated in the code below .

Here is the link of the code on GitHub .Click here to execute the code online.

#include <iostream>
#include <typeinfo>
using namespace std;
template <typename Type> void test_template(Type x){
    cout << x <<endl;
    cout << typeid(Type).name() << endl;
}
int main()
{
   
   test_template<int>(2);
   test_template<double>(3.0);
   return 0;
}

More Meddling with Class templates


Using class templates as function arguments parameters


Here is a piece of code where Template classes are sent as arguments , the comments give a clear explanation on the syntax.Here is the link of the code on Github.Click here to execute the code on Cloud IDE.

#include <iostream>

template<class Type>
class Other {
    
    public:
    	Type x;
    	Other(Type y){
        	x = y;
    	}
};



    void first(const Other<int>& o) {/*One way of specifying the formal parameter*/
    	
    	std::cout << o.x << '\n';
    }
        
 

    template<typename T> void second(const Other<T>& o) {/*Other way of specifyin formal parameter*/
    	/*Has to be decalred as templated function*/
        std::cout << o.x << '\n';
    }


int main(){
    Other<int> other(123);/*initializing template class constructor*/
    first(other);/*sending templated class as parameters*/
    second(other);
}


Now you know how template classes are sent as function parameters and how the actual and formal parameters are defined .
The C++ core of NodeJs contains magnificent pieces of C++ writing and its very essential to have a strong hold of C++ to be able to comprehend the lines written and this blog was an attempt at helping you guys achieve it .We are Getting closer and closer to land on the planet on NodeJs C++ core ….Its just matter of time !!!
Till then …………….As Usual , Happy Coding 😀

Advertisements