-2

i want to provide a swap function for my template class. Here's a simplified version:

template <int size, typename...DataTypes>
class ExampleClass
{
public:
   ExampleClass() : data(size) {}
   void swap(ExampleClass& _Right)
   {
      data.swap(_Right);
   }


protected:
   std::vector<std::tuple<Types...>> data;
}

The swap function doesn't work in this case:

ExampleClass<1,int,float> ec1;
ExampleClass<2,int,float> ec2;
ec1.swap(ec2);

If i swap those vectors of tuples outside without using this class it works:

std::vector<std::tuple<int, float> data1(2);
std::vector<std::tuple<int, float> data2(3);
data1.swap(data2);

Is it possible to provide a swap function using the template class i described first?

max66
  • 65,235
  • 10
  • 71
  • 111
  • Unrelated to your problem, but I suggest you read [What are the rules about using an underscore in a C++ identifier?](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier) Then you will know why `_Right` is not a good name. – Some programmer dude Jan 28 '18 at 17:01

1 Answers1

2

Make the swap function a template:

template<int size2, typename...DataTypes2>
void swap(ExampleClass<size2, DataTypes2...>& _right) { ... }

And of course pass the correct argument to data.swap() (which you don't do know).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Could you explain it more in detail? I'm not able to implement it, sorry... EDIT: Sorry, did just a small mistake. Works now, thank you! –  Jan 28 '18 at 17:08
  • Do you know a similar way to use std::swap and swap the whole class instead of a member variable? –  Jan 28 '18 at 18:45
  • @User19123 Make a non-member `swap` function in the same namespace as the class, calling the member `swap` function on one of the arguments? You can also [specialize](http://en.cppreference.com/w/cpp/algorithm/swap#Specializations) the [`std::swap`](http://en.cppreference.com/w/cpp/algorithm/swap) function. – Some programmer dude Jan 28 '18 at 19:33