1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
#include <vector>
#include <type_traits>
#include <stdexcept>
#include <string>
namespace detail
{
template < typename T1, typename T2 > struct common_type : std::common_type<T1,T2> {} ;
template < typename T1, typename T2 > // specialisation for the common vector type between two vectors
struct common_type< std::vector<T1>, std::vector<T2> >
{
using type = std::vector< typename common_type<T1,T2>::type > ;
};
}
template< typename T1, typename T2 >
auto operator+( const std::vector<T1>& vec1, const std::vector<T2>& vec2 )
{
const std::size_t len = vec1.size();
if(len != vec2.size()) throw std::invalid_argument ("Operand vectors have mismatched sizes.");
std::vector< typename detail::common_type<T1,T2>::type > ret(len);
for (size_t i = 0; i < len; i++) { ret[i] = vec1[i] + vec2[i]; }
return ret;
}
int main()
{
const std::vector< std::string > vec1 { "abcd", "efgh", "ijkl" } ;
const std::vector< const char* > vec2 { "+mnop", "+qrst", "+uvwxyz" } ;
for( const auto& v : vec1 + vec2 ) std::cout << v << ' ' ;
std::cout << '\n' ;
const std::vector<std::vector<double>> a = { {1.1,2.2,3.3}, {4.4,5.5,6.6} };
const std::vector<std::vector<int>> b = { {4,5,6}, {7,8,9} };
for( const auto& vec : a + b )
{
std::cout << "{ " ;
for( const auto& v : vec ) std::cout << v << ' ' ;
std::cout << "} " ;
}
std::cout << '\n' ;
}
| |