问题描述
在下面的代码中,我正在为int值和对象做乘法可变参数模板.它适用于所有原始类型.它也仅适用于2个对象.但是,当我使用两个以上的自变量对象相乘时,代码不会编译.
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
对于2个以上的对象乘法,如何解决此问题?乘法是按左联想完成的.
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) )
扩展为 A(1)*乘法(B(1),B(1))
.由于您没有重载 operator *(const B& ;, const B&)
,因此会出现编译错误.
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.
这篇关于可变参数模板对象乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!