Search code examples
c++c++11variadic-templatesswaptemplate-classes

Ignore template argument to provide swap function


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?


Solution

  • 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).