When you call a function, what do these do<>

I am studying cire's solution here:
http://www.cplusplus.com/forum/beginner/108849/#msg592118

To understand it I have been learning about templates and typedef, but I can't find the right search to learn what these do <> when you call a function such as cire's does within main.

1
2
3
4
5
6
7
8
9
int main()
{
    typedef unsigned short num_type;

    num_type playerNumber = get<num_type>("Enter a number between 1 and 100 and I will guess it: ", 
                                            [](const num_type& val) { return val > 0 && val < 101; });

    std::cout << playerNumber << '\n';
}

What happens when you use
 
get<num_type>

?
get() is a function template and <> tells the complier the type a particular function call is instantiated for. So in the example, get<> is instantiated for num_type which is typedef for unsigned short
for template functions the type parameter can sometimes be done without if the compiler can guess the type information from the args as in the following example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>

template <typename T>
void guessArgs(const T& t)
{
    std::cout << t << "\n";
}

int main()
{
    int t = 42;
    guessArgs(t);//type of t is known
    guessArgs<double>(3.14);
    //guessArgs(3.14);also valid
}

however in the example you link to the type parameter would not be known at compile time as it comes from user-input, so the function is 'prepared' so to say by passing it the template parameter
Last edited on
Topic archived. No new replies allowed.