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
|
#include <iostream>
#include <vector>
template< typename T1, typename T2 > struct plus_result // rudimentary expression template
{
plus_result( const std::vector<T1>& a, const std::vector<T2>& b ) : a(a), b(b) {}
template < typename RESULT_TYPE >
operator std::vector<RESULT_TYPE>() const // evaluated when required
{
if( a.size() < b.size() ) return plus_result<T2,T1>(b,a) ;
std::vector<RESULT_TYPE> result( a.begin(), a.end() ) ;
for( std::size_t i = 0 ; i < b.size() ; ++i ) result[i] += b[i] ;
return result ;
}
const std::vector<T1>& a ;
const std::vector<T2>& b ;
};
template< typename T1, typename T2 > // return expression template
plus_result<T1,T2> operator+ ( const std::vector<T1>& a, const std::vector<T2>& b ) { return {a,b} ; }
int main()
{
const std::vector<int> a = { 1, 2, 3, 4, 5 };
const std::vector<double> b = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
const std::vector<float> vec_flt = a + b ; // plus_result<int,double>(a,b).operator std::vector<float>() ;
for( float f : vec_flt ) std::cout << f << ' ' ;
std::cout << '\n' ;
// note: int + double => long long results in loss of fractional part
const std::vector<long long> vec_ll = a + b ; // plus_result<int,double>(a,b).operator std::vector<long long>() ;
for( long long v : vec_ll ) std::cout << v << ' ' ;
std::cout << '\n' ;
}
|