3

I have just a simple question, check this code please:

template < typename A >
void foo( A a )
{ cout<<"1\n"; };

template< >
void foo<float>( float a )
{  cout<<"2\n"; }

void foo( float a )
{ cout<<"3\n"; }


int main()
{
    foo<float>( 1.0f );
}

Compiled with g++ 4.7.2 works of course, but what is not clear to me is why the output is "2" instead of "3".

As far as I remember a non template function shall be always preferred towards a template one, so why is called the specialized foo?

Thanks

fjanisze
  • 1,234
  • 11
  • 21
  • 1
    You would need to call `foo(1.0f)` to get the non-template. – juanchopanza Dec 06 '12 at 11:06
  • `foo` is the name of a template function specialisation (which you happen to have explicitly specialised; if you hadn't, you would see "1" instead). If you don't provide the `<...>` syntax, overload resolution will indeed prefer the non-template function. – j_random_hacker Dec 06 '12 at 11:06
  • See also http://www.gotw.ca/gotw/049.htm – johnsyweb Dec 06 '12 at 11:11
  • 1
    @jrok: No, since `foo` and `foo` are distinct names. The fact that writing just `foo` when calling a function *also* causes function templates like `foo` to be looked up is just a "feature" of overload resolution. – j_random_hacker Dec 06 '12 at 11:12

1 Answers1

8

You specifically are using the specialized version. Had you done this:

template <typename T>
void foo(T a) {
    std::cout << "1" << std::endl;
}

void foo(float a) {
    std::cout << "2" << std::endl;
}
int main(void) {
    foo(1.0f);
}

than it would have picked the non templated version.

gvd
  • 1,823
  • 13
  • 18