Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand templates

Tags:

c++

templates

I wrote a short example of the confusion that I'm having here:

#include <iostream>

template <typename T>
T Add (T t1, T t2)
{
    std::cout << "<typename T>" << std::endl ;
    return t1 + t2 ;
}

template <int>
int Add (int n1, int n2)
{
    std::cout << "<int>" << std::endl ;
    return n1 + n2 ;
}

template <>
int Add (int n1, int n2)
{
    std::cout << "<>" << std::endl ;
    return n1 + n2 ;
}

int main (void) 
{
    Add (5, 4) ;
    Add <int> (5, 4) ;
    Add <> (5, 4) ;

    return 0 ;
}

The output of this is:

<>  
<>  
<>  

So I'm thinking, okay, the most explicit specialization gets priority.
But then I remove:

template <>
int Add (int n1, int n2)
{
    std::cout << "<>" << std::endl ;
    return n1 + n2 ;
}

And the output is:

<typename T>  
<typename T>  
<typename T>  

Why doesn't template <int> version get called?
What would cause it to get called?
Why is the purpose of that syntax?

like image 951
jliv902 Avatar asked Jan 21 '14 19:01

jliv902


1 Answers

The second overload expects an integer, not a type. You'd call it with

Add< 42 >( 1, 2 );

Live example

To clarify: The second is an independent overloaded function called Add, not a specialization. You were probably thinking of something like:

template <>
int Add<int>(int n1, int n2)
{
    std::cout << "<T=int>" << std::endl ;
    return n1 + n2 ;
}

which is exactly the same as the last specialization you wrote and which would thus conflict with it (redefining it). Live example

like image 193
Daniel Frey Avatar answered Oct 09 '22 22:10

Daniel Frey