Template programming

Hello,

if we have the following function

1
2
3
4
5
6
7
template<typename T> 

void mySwap(T& a, T& b) {
  T temp = a;
  a = b;
  b = temp;
}

What requirements does the type T have if T is a class? I've read that T needs to have a copy constructor and assignment operator(i.e. = operator). First of all, don't all classes have the = operator by default?

And in this case, do we need to implement our own copy constructor/assignment operator, if none of the data members of the class are pointers? Let's say the data members are string, int and double.
First of all, don't all classes have the = operator by default?

If you don't create one, and you don't specify that there isn't to be one, you get a simple one for free. But you can specify that a class doesn't have one, or you could specify privacy levels that mean this code can't use it, and then those classes would not work with this code.


And in this case, do we need to implement our own copy constructor/assignment operator, if none of the data members of the class are pointers? Let's say the data members are string, int and double.

string, int and double all come with a provided operator= and a whole bunch of others, so there's no need for you to write one.
Last edited on
Thanks! what happens if you use the operator> on two objects of the same class, and you haven't overloaded it?
Rule of three/five/zero discusses the operator= https://en.cppreference.com/w/cpp/language/rule_of_three


The operator> is easy to test:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <utility>  // std::rel_ops

class Foo {};

bool operator< (const Foo&, const Foo& ) { return true; }

int main()
{
  // using namespace std::rel_ops;
  Foo a;
  Foo b;
  std::cout << (a > b); // error: no match for 'operator>'
}

We do get an error, for we don't supply operator> for our class Foo.

However, if we do uncomment line 10, then there is no error.
See http://www.cplusplus.com/reference/utility/rel_ops/
Topic archived. No new replies allowed.