fork(2) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <utility>
  4.  
  5. template<typename T, typename U, typename A1, typename A2>
  6. decltype(std::declval<T>() * std::declval<U>() + std::declval<T>() * std::declval<U>())
  7. dot_product( std::vector<T, A1> const& lhs, std::vector<U, A2> const& rhs )
  8. {
  9. decltype(std::declval<T>() * std::declval<U>() + std::declval<T>() * std::declval<U>()) sum = 0;
  10. for( std::size_t i = 0; i < lhs.size() && i < rhs.size(); ++i ) {
  11. sum += lhs[i] * rhs[i];
  12. }
  13. return sum;
  14. }
  15. template<typename LHS>
  16. struct half_dot {
  17. LHS lhs;
  18. half_dot( LHS&& lhs_ ):lhs(std::forward<LHS>(lhs_)) {}
  19. template<typename RHS>
  20. decltype( dot_product( std::declval<LHS>(), std::declval<RHS>() ) )
  21. operator*( RHS&& rhs ) const {
  22. return dot_product( std::forward<LHS>(lhs), std::forward<RHS>(rhs) );
  23. }
  24. };
  25. struct dot_t {};
  26. template<typename LHS>
  27. half_dot<LHS> operator*( LHS&& lhs, dot_t ) {
  28. return {std::forward<LHS>(lhs)};
  29. }
  30. static dot_t dot;
  31.  
  32. int main() {
  33. std::vector<int> foo = {1,2,3};
  34. std::vector<int> bar = {3,2,1};
  35. std::cout << (foo *dot* bar) << "\n";
  36. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
10