C++ Type vs. Non-Type Template Deduction Question

70 Views Asked by At

I have a question about C++ template deduction when there are two matches: one typed and the other non-typed. In the following situation:

// First
template<int>
void g(int a)
{
...
}

// Second
template<class A>
void g(A a)
{
...
}

int a = 1;
g(a);

the Second template is favored, while if the non-typed template parameter is given a default value:

// First
template<int m = 1>
void g(int a)
{
...
}

// Second
template<class A>
void g(A a)
{
...
}

int a = 1;
g(a);

the First template is favored. Why?? Which rules are in play here? Thanks.

1

There are 1 best solutions below

0
Erik Man On

In the first case:

// First
template<int>
void g(int a)
{
...
}

is only invokable with a specified template parameter, for instance like this g<1>(42);. There is no way for the compiler to deduce the value to use for the int, so the first function does not participate in overload resolution.

In the second case there is a default value, so now both functions are part of overload resolution and then the int version is a closer match than deducing that A = int.