Question

Playing around with templates and specializations trying to understand the rules I used the following code.

template <typename T> // A
void foo(T);

template <typename T> // B
void foo(T *);

template <>
void foo<int *>(int *); // C

int _tmain(int argc, _TCHAR* argv[])
{
    int n=0;
    int *p = &n;
    foo(p);

    return 0;
}

Which version of foo would you think gets called here? I was expecting C. But that's not what happens. It's actually B. But why is that? Isn't C the best match and a specialization of B?

However, if I the change C to

template <>
void foo<>(int *) // C

or

template <>
void foo<int>(int *) // C

Then the foo() call gets resolved to C? So I'm not fully understanding the syntax and the meaning of what goes between the angled brackets in void foo <>.

Would appreciate somebody clarifying this.

Thanks.

Was it helpful?

Solution

C isn't a specialization of B. The entity between the angle brackets in C, int*, is the value of the template parameter T. If you're specializing A, then T needs to be the same as the type of the parameter, which it is. If you're specializing B, then the parameter needs to be T*, not T.

When you change the declaration of C to

template <>
void foo<int>(int *) // C

C becomes a specialization of B but not A, by the same reasoning.

In both cases, B wins overload resolution. In the first case, there's no explicit specialization of B, so B gets called. In the second case, C, the explicit specialization of B, gets called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top