Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template specialization in C++

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";
}
like image 881
Zubizaretta Avatar asked Dec 21 '22 06:12

Zubizaretta


1 Answers

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.

like image 186
Kerrek SB Avatar answered Dec 24 '22 01:12

Kerrek SB