Jaskamal Kainth

C++ Notes

Template explicit vs implicit specialization

    #include <iostream>
    using std::cout;

    // Main template
    template<class T>
    void f(T n) {
        cout << 2;
    }
    // Template specialization
    template<> 
    void f(const int n) {
        cout << 1;
    }

    int main() {
        int n = 11;
        f(n); 
    }

Code outputs 2.

For the function call f(n), since ‘n’ is of int type, the template arguement T is deduced as T = int.

The Explicit specialization

 template<> void f(const int n)

has type T as const int which is not same as int so it doesn’t match.

Therefore the Implicit instantiation happens with T = int.

In the case if we pass a const int to the function f, the code will output 1.

If a specialized template is present, compiler first checks with the specialized version and then the main template. Compiler first checks with the most specialized version by matching the passed parameter with the data type(s) specified in a specialized version.