Example of Non-type parameters for templates
Write a C++ Program to demonstrate an Example of Non-type parameters for templates. Here’s a Simple C++ Program to demonstrate an Example of Non-type parameters for templates in C++ Programming Language.
What are Templates in C++ ?
Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.
There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector <int> or vector <string>..
Function Template :
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list)
{
// body of function
}
Class Template :
Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here:
template <class type> class class-name
{
.
.
.
}
Below is the source code for C++ Program to demonstrate an Example of Non-type parameters for templates which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
/* C++ Program to demonstrate an Example of Non-type parameters for templates */ #include <iostream> using namespace std; template <class T, int N> class mysequence { T memblock [N]; public: void setmember (int x, T value); T getmember (int x); }; template <class T, int N> void mysequence<T,N>::setmember (int x, T value) { memblock[x]=value; } template <class T, int N> T mysequence<T,N>::getmember (int x) { return memblock[x]; } int main () { mysequence <int,5> myints; mysequence <double,5> myfloats; myints.setmember (0,100); myfloats.setmember (3,3.1416); cout << myints.getmember(0) << '\n'; cout << myfloats.getmember(3) << '\n'; return 0; }
OUTPUT : :
/* C++ Program to demonstrate an Example of Non-type parameters for templates */ 100 3.1416 Exit code: 0 (normal program termination)
Above is the source code and output for C++ Program to demonstrate an Example of Non-type parameters for templates which is successfully compiled and run on Windows System to produce desired output.
If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach upto you in the short interval.
Thanks for reading the post….