Variadic templated Multiplication Objects

In the code below, I make various variation patterns for int values ​​as well as for objects. It works for all primitive types. It also works for only two objects. But the code does not compile when I use more than two argument objects to propagate.

multiply(1, 2, 3, 4, 5, 6) //works correcyly multiply( A(1), B(1)) //works correctly multiply( A(1), B(1), B(1) ); //compile time Error multiply( A(1), B(1), B(1), B(1) ); //compile time Error 

How can I solve this problem for more than two objects? Multiplication is performed as a left associative.

 #include <iostream> #include <assert.h> #include <cstddef> #include <typeinfo> #include <stdlib.h> using namespace std; template <typename...> struct MulTs; template <typename T1> struct MulTs<T1> { typedef T1 type; }; template <typename T1, typename... Ts> struct MulTs<T1, Ts...> { static typename MulTs < Ts...>::type makeTs(); //a static T1 makeT1(); //b typedef decltype(makeT1() * makeTs()) type; //c }; template <typename T> T multiply(const T& v) { return v; } template <typename T1, typename... Ts> auto multiply(const T1& v1, const Ts&... rest) -> typename MulTs<T1, Ts...>::type //instead of the decltype { return v1 * multiply(rest...); } struct B; struct A { friend A operator*(const A &, const B &); friend ostream & operator<<(ostream &os, const A &a); A(int val = 0) : i(val) {} private: const int i; }; struct B { friend A operator*(const A &a, const B &b) { return A(ai * bi); } B(int val = 0) : i(val) {} private: const int i; }; ostream &operator<<(ostream &os, const A &a) { return os << ai; } int main() { cout << multiply(1, 2, 3, 4, 5, 6) <<endl;//works correcyly cout << multiply( A(1), B(1))<<endl; //works correctly //cout << multiply( A(1), B(1), B(1) ); //compile time Error } 
0
source share

All Articles