简体   繁体   中英

variadic templated Object multiplication

In the below code I am doing multiplication variadic templates for the int values and also for the Objects. It works for the all primitive types. It also works for the only 2 objects. But the code doesn't compile when I use more than 2 arguments objects into multiply.

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 could I solve this problem for the more than 2 object multiplication? Multiplication is done as 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(a.i * b.i);
    }
    B(int val = 0) : i(val) {}
private:
    const int i;
};

ostream &operator<<(ostream &os, const A &a) {
    return os << a.i;
}

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 
}
multiply( A(1), B(1), B(1) )

Expands to A(1) * multiply(B(1), B(1)) . Since you don't have overloaded operator *(const B&, const B&) you're getting compile error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM