templates - why are the calls ambiguous?

P

Piotrek

Below are two short programs:

1)

template<class T> void foo(){}

int main()
{
&foo<int>;
return 0;
}

2)

template<int N> void foo() {int i = N;}

int main()
{
&foo<4>;
return 0;
}

None of them compiles when tested here:

http://codepad.org/

and compilation fails with "error: statement
cannot resolve address of overloaded function"
(which can be bypassed for program 2. with
(void(*)())&foo<4> instead of &foo<4>)

while both compile when tested here:

http://www.compileonline.com/compile_cpp11_online.php

Two things:

1) I realize it's caused by a rule saying a template
name is considered to always name a set of overloaded
functions (hence the ambiguity), but is there any reason
behind it other than "because the standard says so"?
To me it looks like in each case there's only one
possible instantiation with a given type/value, so where
does the ambiguity come from? After all, what's
the difference between my example and perfectly valid:

template<class T> void foo(){}

int main()
{
foo<int>();
return 0;
}

?

2) Why do the examples compile fine with the second
compiler? Is the discussed rule loosened or removed
from C++11 standard?
 
Ö

Öö Tiib

1) I realize it's caused by a rule saying a template
name is considered to always name a set of overloaded
functions (hence the ambiguity), but is there any reason
behind it other than "because the standard says so"?

It did not. 13.4 was not clear enough about intentions
in C++98 so implementations did as they wanted.
2) Why do the examples compile fine with the second
compiler? Is the discussed rule loosened or removed
from C++11 standard?

An issue was fixed and standard's intentions clarified.
See that issue:
http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#115

Like you see the defect report was raised past millennia.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top