[C++] Function and Class template

发布于 2024-03-19  1361 次阅读


Please refresh the page if equations are not rendered correctly.
---------------------------------------------------------------

1. Function template

1.1 Example 1

template <class retType, class argType>
retType cast(argType a) {
    return (retType)a;  // Explicit type casting
}

Function templates are a way to achieve code reusability and generic programming in C++. They are special functions that can operate with generic types. This allows a function to be called with arguments of many different types.

In the provided code, template <class retType, class argType> is the template declaration. The keyword template is followed by template parameters enclosed in angle brackets <>. Here, retType and argType are the template parameters which represent types. These types are placeholders and will be replaced by actual types when the function is invoked.

The function cast takes one argument a of type argType and returns a value of type retType. Inside the function, (retType)a is an explicit type casting. It converts the argument a from argType to retType.

For example, if you call cast<int, double>(3.14), the function will convert the double value 3.14 to int and return 3. Similarly, cast<char, int>(65) will convert the int value 65 to char and return 'A'.

This function template can be used for casting between any two types that support explicit type casting. It's a very flexible and reusable piece of code.

1.2 Example 2

template <class T>
T GetMax (T a, T b) {
    T result;
    result = (a>b)? a : b;
    return (result);
}

In the provided code, template <class T> is the template declaration. The keyword template is followed by template parameters enclosed in angle brackets <>. Here, T is the template parameter which represents a type. This type is a placeholder and will be replaced by an actual type when the function is invoked.

The function GetMax takes two arguments a and b of type T and returns a value of type T. Inside the function, a variable result of type T is declared. The line result = (a>b)? a : b; uses the ternary operator to compare a and b. If a is greater than b, a is assigned to result. Otherwise, b is assigned to result.

Finally, the function returns result, which will be the greater of the two input values.

For example, if you call GetMax<int>(3, 7), the function will return 7. If you call GetMax<char>('a', 'z'), the function will return 'z'.

This function template can be used to compare any two values of a type that supports the greater than operator (>). It's a very flexible and reusable piece of code.

1.3 All code

#include <iostream>

using namespace std;

/* Function template */
template <class T>
T add(T a, T b) {
    return a + b;
}

template <class retType, class argType>
retType cast(argType a) {
    return (retType)a;  // Explicit type casting
}

template <typename T>
void print(T data) {
    cout << data << endl;
} 

template <class T>
T GetMax (T a, T b) {
    T result;
    result = (a>b)? a : b;
    return (result);
}

int main() {
    // Implicitly specifying the type of the template
    cout << add(3, 4) << endl; 
    // Explicitly specifying the type of the template
    cout << add<int>(3, 4.2) << endl; 
    // Implicitly specifying the type of the template
    cout << add(3.5, 4.) << endl; 
    // Explicitly specifying the type of the template
    cout << add<double>(3.5, 4.4) << endl; 

    // // Error: deduced conflicting types for parameter 'T' ('double' and 'int')
    // cout << add<double>(3.5, 4) << endl; 

    cout << cast<int, double>(3.5) << endl;
    cout << cast<long, int>(3) << endl;

    double data;
    cout << "Enter a number: ";
    cin >> data;

    print(data);

    long l = GetMax<long>(10, 20);
    cout << l << endl;

    return 0;
}

2. Class template

2.1 Example

template <class A, int N>
class mysequence {
    A memblock [N];
  public:
    void setmember (int x, A value);
    A getmember (int x);
};

The active selection is a class template in C++. Class templates are a way to achieve code reusability and generic programming. They allow classes to operate with generic types, which means you can create objects of the class with different types.

In the provided code, template <class A, int N> is the template declaration. The keyword template is followed by template parameters enclosed in angle brackets <>. Here, A is a type parameter and N is a non-type parameter. A is a placeholder for any type and N is a placeholder for an integer value. These placeholders will be replaced by actual type and value when an object of the class is created.

The class mysequence has one member variable memblock, which is an array of N elements of type A. This means that the size and type of the array memblock can be different for different objects of the class mysequence.

The class has two member functions. The function setmember takes an integer x and a value of type A, and it doesn't return anything. The function getmember takes an integer x and returns a value of type A. The implementation of these functions is not shown in the selection.

For example, you can create an object of the class with int type and size 5 like this: mysequence<int, 5> seq;. Then you can use the setmember function to set the value of an element in the array, and the getmember function to get the value of an element.

This class template can be used to create a sequence (array) of any type and any size. It's a very flexible and reusable piece of code.

2.2 All code

#include <iostream>

using namespace std;

/* Class template */
template <class T>
class mypair {
    T a, b;
  public:
    mypair (T first, T second) {
        a = first;
        b = second;
    }
    T getmax ();
};

template <class T>
T mypair<T>::getmax () {
    T retval;
    retval = (a>b)? a : b;
    return retval;
}

template <class A, int N>
class mysequence {
    A memblock [N];
  public:
    void setmember (int x, A value);
    A getmember (int x);
};

template <class A, int N>
void mysequence<A,N>::setmember (int x, A value) {
    memblock[x]=value;
}

template <class T, int N>
T mysequence<T,N>::getmember (int x) {
    return memblock[x];
}


int main() {
    cout << "Class template" << endl;
    cout << "===============" << endl;
    mypair<int> myobject (100, 75);
    cout << myobject.getmax() << endl;
    mypair<double> myobject2 (100.0, 75.0);
    cout << myobject2.getmax() << endl;

    mysequence<int,5> myints; // create an array of 5 elements of type int
    mysequence<double,5> myfloats; // create an array of 5 elements of type double
    myints.setmember (0,100); // set value of first element of myints = 100
    myfloats.setmember (3,3.1416); // set value of 4th element of myfloats = 3.1416
    cout << myints.getmember(0) << endl;
    // get all the values of myints
    for (int i=0; i<5; i++) {
        cout << myints.getmember(i) << " ";
    }
    cout << endl;

    cout << myfloats.getmember(3) << endl;
    // get all the values of myfloats
    for (int i=0; i<5; i++) {
        cout << myfloats.getmember(i) << " ";
    }

    return 0;
}
Everything not saved will be lost.
最后更新于 2024-03-19