~/okanakyuz
← all posts

Template

A short code review of C++ function templates: explicit instantiation, explicit specialization and non-type template parameters.

8 March 2020updated 25 November 20261 min read

C++ template code

Here is a short review code for templates.

#include <iostream>
#include <typeinfo>

template<typename T>
T maxFunc (T x, T y){
    std::cout << typeid (T).name() << " maxFunc ("
              << typeid (T).name() << " x, "
              << typeid (T).name() << " y)"
              << "("<< x << "," << y << ")" << std::endl;
    return x > y ? x : y;
}

// Explicit Instantiation
template char maxFunc(char x, char y);

// Explicit Specialization
template<> int * maxFunc (int * x, int * y ){
    std::cout << "template<> int * maxFunc (int * x, int * y )"
              << "(" << *x << "," << *y << ")" << std::endl;
    int * ret;
    ret = *x > *y ? x : y;
    return ret;
}

// non-type template parameter
template <int i>
void doprint(){
    std::cout << "Doprint" << i << std::endl;
}

int main()
{
    std::cout <<  maxFunc(3,2) << std::endl;
    std::cout <<  maxFunc<double>(3.2,2) << std::endl;
    int * a {new int};
    int * b {new int};
    *a = 2;
    *b = 3;
    std::cout <<  *maxFunc(a,b) << std::endl;
    delete a;
    delete b;

    doprint<2>();

    return 0;
}

Explicit instantiation forces the compiler to create a version of the code for the given type, even if nothing calls it yet.

Explicit specialization is the way to create an alternative implementation of a template function for a specific type. Here the int * version compares the values, not the addresses.

doprint takes a value, not a type, as its template parameter. I wrote more about it in Non-type Template in Array.

Update (2026): C++20 added concepts, so you can say what a type must support instead of getting a long error from inside the template:

#include <concepts>

template<std::totally_ordered T>
T maxFunc(T x, T y){
    return x > y ? x : y;
}

C++20 also has abbreviated function templates, like void print(const auto& x). Every auto parameter is a separate template parameter, so maxFunc(auto x, auto y) would accept two different types, which is not what we want here.