Monday, November 15, 2021

(C++) How to pass a variable type to a function

 E.g If you need to pass info like this:

void foo(type){
    // Other actions based on type
    cout << sizeof(type);
}

This cannot be done i.e. the type cannot be passed as a parameter since it is not a object and they do not exist at run time. They are only used by the compiler for type information building into the code. This can be instead fullfilled by templatinzing the function.

A template behaves in the following way:

template <typename T>

void foo(other_args) {

    // Other relevant data.

    T  somevar;

    cout << sizeof(somevar) << "    " <<sizeof(T);

}

Typenames can be also used to templatize classes in a similar fashion.