Home > Blockchain >  Why is the template specialization function not being accessed
Why is the template specialization function not being accessed

Time:10-04

Problem Description

In the following code we have 2 classes A and B whereB inherits from A. We also have 2 template functions test(T &t) and test(A &a). The output of the code is "A1".

Why the test(A &a) function isn't being used in this example?


// Online C   compiler to run C   program online
#include <iostream>
class A {};
class B: public A {};

template<typename T>
void test(T &t){std::cout <<"A1";}
template<>
void test(A& a){std::cout <<"A2";}

// If we put test(A& a) before test(T &t) we get the compilation error
// 'test' is not a template function

int main() {
    A *a = new B();
    test(a);
    delete a;
    return 0;
}

CodePudding user response:

You're trying to pass a value of type A* to a function accepting A&. These are incompatible types, a pointer is not a reference. So the specialization test(A&) isn't considered, and the main template is used with T deduced as A*.

If we change the call test(a) to test(*a), then the program will print A2.

#include <iostream>
class A {};
class B: public A {};

template<typename T>
void test(T &t){std::cout <<"A1";}
template<>
void test(A& a){std::cout <<"A2";}

// If we put test(A& a) before test(T &t) we get the compilation error
// 'test' is not a template function

int main() {
    A *a = new B();
    test(*a);              // <==== Here
    delete a;
    return 0;
}

(live demo)

  • Related