Template Constructor Confusion

In definition of pair class:

1
2
3
4
5
6
7
8
9
10
11
12
template <class T1, class T2> struct pair
{
  typedef T1 first_type;
  typedef T2 second_type;

  T1 first;
  T2 second;
  pair() : first(T1()), second(T2()) {}
  pair(const T1& x, const T2& y) : first(x), second(y) {}
  template <class U, class V>
    pair (const pair<U,V> &p) : first(p.first), second(p.second) { }
}


See bolded portion. How should I read this? I was under the impression that the function template "template <typename T> void example(T one, T two)" would be called by "example<int,int>(1,3)". But the following code does not compile:

1
2
3
4
5
6
7
#include <utility>

int main() {
    std::pair<int,int> p(1,2);
    std::pair<long,long><int,int> pp(p); //error
    std::pair<long,long> pp(p); //correct
}


I guess I'm trying to find out how function templates behave when contained in class templates.

Also, is it just me, or do the typedef's here add nothing?
Last edited on
The highlighted member function is the copy constructor. An example where it's called is:
1
2
3
4
5
6
7
8
9
#include <utility>
#include <string>

int main()
{
    pair<int, string> a(1, "a string");
    pair<int, string> b(a); // constuct using copy constructor
    return 0;
}


The 2nd declaration in your example is incorrect--the syntax is incorrect.
Last edited on
I was under the impression that the function template "template <typename T> void example(T one, T two)" would be called by "example<int,int>(1,3)"


This is almost correct.

Your example,

template <typename T> void example(T one, T two);

should be called as in the following:

example<int>(1, 3)

Note that you only have one template parameter, T, in your function definition. Even though you *use* T twice in the function prototype, there is only one template variable, which is why you only need to type example<int>, rather than example<int, int>.

If you wanted two template variables, you could make your function prototype look like this:

template <typename T1, typename T2> void example(T1 one, T2 two);

which could be called like this:

example<int, int>(1, 3);

As an extra note, either of those example functions could be called simply with

example(1, 3);

In this particular case, C++ is smart enough to figure out that the arguments you are giving the example function are ints, so you can omit the template arguments. As soon as you have any ambiguity this will no longer work though.
Topic archived. No new replies allowed.