For a C++ exercise for school I need to overload the + operator to concatenate 2 arrays. And I need to do that in a generic class.
for ex:
a1 = {1, 3, 4}
a2 = {2, 3, 5, 6}
=> a = {1, 3, 4, 2, 3, 5, 6}
And I have this code but it's not working.
#include <iostream>
#include <array>
using namespace std;
template <class T>
T operator+(const T& a1, const T& a2)
{
T a;
for (typename T::size_type i = 0; i < a1.size() + a2.size; i++) {
if (i < a1.size()) {
a[i] = a1[i];
} else {
a[i] = a2[i];
}
}
return a;
}
int main()
{
array<int,3> a1 = { 1, 3, 4 };
array<int,4> a2 = { 2, 3, 5, 6 };
array<int,7> a3 = a1 + a2;
for (int i = 0; i < 5; i++)
cout << a1[i] << '+' << a2[i] << '=' << a3[i] << ' ';
cout << endl;
return 0;
}
This code doesn't work, this is what I receive in the console:
main.cpp:32:24: error: no match for ‘operator+’ (operand types are ‘std::array’ and ‘std::array’)
array<int,7> a3 = a1 + a2;
~~~^~~~
main.cpp:15:3: note: candidate: template T operator+(const T&, const T&)
T operator+(const T& a1, const T& a2)
What should I do to resolve the problem? And another question, does this code use generic class? Any feedback will be appreciated!
T operator+(const T& a1, const T& a2)is all the sameTs, butarray<int,3>,<array<int,4>andarray<int,4>are different types+but the imlementation looks like you want to concatenate. What do you actually want?