Besides the template arguments that are preceded by the class or typename keywords , which represent types, templates can also have regular typed parameters, similar to those found in functions. As an example, have a look at this class template that is used to contain sequences of elements:// sequence template#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:100,3.1416 It is also possible to set default values or types for class template parameters. For example, if the previous class template definition had been: template <class T=char, int N=10> class mysequence {..}; We could create objects using the default template parameters by declaring: mysequence<> myseq; Which would be equivalent to: mysequence<char,10> myseq;
C++
Topic: Templates
Explain about Non-type parameters for templates ?
Browse random answers:
What is a template?
Can we have "Virtual Constructors"?
How can you force instantiation of a template?
What is namespace?
When is a template a better solution than a base class?
How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#?
What is a friend function & its advantage?
Differentiate between a template class and class template?
What is the Standard Template Library (STL)?
When is a template a better solution than a base class?
What are the Function templates ?
What are Class templates ?
Explain about Template specialization ?
Explain about Non-type parameters for templates ?
Explain the Templates and multiple-file projects ?
What are the syntax and semantics for a function template?
Differentiate between a template class and class template.
My compiler says that a member of a base class template is not defined in a derived class template. Why is it not inherited? template<typename T>class base {public: void base_func();};template<typename T>class derived : public base<T> {public: void derived_func() { base_func(); // error: base_func not defined }};
Is it possible to specialise a member function of a class template without specialising the whole template?
Why do I need to add "template" and "typename" in the bodies of template definitions?
Is there a difference between a function template and a template function, or between a class template and a template class?