Templeate in C++
- Generic programming, which entails writing code in a style that is independent of any specific type, is built on templates.
- A template is a model or recipe for developing a universal class or function. Generic programming is demonstrated through library containers like iterators and algorithms, which were created utilising the template notion.
- Each container has a unique definition, however there are numerous alternative types of vectors that can be defined, such as vectors that are int or strings.
- Both functions and classes can be defined using templates; let's look at how they operate.
- Types of Templates
- function Templates
- Class Templates
- Variadic Templates.
- #include
- #include
- #include
- #include
- #include
- using namespace std;
- template
- class Stack
- {
- private:
- vector
elems; // elements - public:
- void push(T const&); // push element
- void pop(); // pop element
- T top() const; // return top element
- bool empty() const { // return true if empty.
- return elems.empty();
- }
- };
- template
- void Stack
::push (T const& elem) { - // append copy of passed element
- elems.push_back(elem);
- }
- template
- void Stack
::pop () { - if (elems.empty()) {
- throw out_of_range("Stack::pop(): empty stack");
- }
- // remove last element
- elems.pop_back();
- }
- template
- T Stack
::top () const { - if (elems.empty()) {
- throw out_of_range("Stack::top(): empty stack");
- }
- // return copy of last element
- return elems.back();
- }
- int main() {
- try {
- Stack
intStack; // stack of ints - Stack
stringStack; // stack of strings - // manipulate int stack
- intStack.push(7);
- cout
- // manipulate string stack
- stringStack.push("hello");
- cout
- stringStack.pop();
- stringStack.pop();
- } catch (exception const& ex) {
- cerr
- return -1;
- }
- }
- PREPROCESSOR :
Only characters that are white space may come before a preprocessor directive on a line; all preprocessor directives start with #. Preprocessor directives do not terminate in a semicolon because they are not C++ statements (;).
A #include directive has already been used in each case. Using this macro, a header file can be added to the source file.
C++ supports a number of preprocessor directives, including #include, #define, #if, #else, and #line. Let's look at some crucial instructions.