4

I've been trying to understand template specializations. Why is this generating an error (specialization of 'T foo(T, T) [with T = int]' after instantiation)

template <class T> T foo(T a, T b);

int main()
{
    int x=34, y=54;
    cout<<foo(x, y);
}

template <class T> T foo(T a, T b)
{
    return a+b;
}

template <> int foo<int>(int a, int b)
{
    cout<<"int specialization";
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
Zubizaretta
  • 157
  • 1
  • 9

3 Answers3

8

The standard demands that all template definitions must be known at the time of instantiation, and that every translation unit see the same definition. Otherwise your program is ill-formed (and in fact no diagnostic is required).

(So to solve this, just put all the template definitions at the top of the program.)

Remember that template functions aren't functions, just templates. Think of them as a code generation tool.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
3

The explicitly specialized template function foo() should be visible before it can be called/Instantiated.

In fact the above rule applies to all Template functions.

Solution:
Move the template specialization for foo() before your main().

Following should work just fine:

template <class T> T foo(T a, T b);

/*Should be visible before instantiation*/
template <> int foo<int>(int a, int b)
{
    cout<<"int specialization";
}

int main()
{
    int x=34, y=54;
    cout<<foo(x, y);
}

template <class T> T foo(T a, T b)
{
    return a+b;
}
Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

Don't do that.

What Herb Sutter said:

If you're writing a function base template, prefer to write it as a single function template that should never be specialized or overloaded, and then implement the function template entirely as a simple handoff to a class template containing a static function with the same signature.

See: http://www.gotw.ca/publications/mill17.htm

xis
  • 24,330
  • 9
  • 43
  • 59