bap*_*ste 0 c++ templates c++03
在我的C++代码中,我有一个Matrix类,并且编写了一些运算符来乘以它们.我的类是模板化的,这意味着我可以有int,float,double ...矩阵.
我猜运算符过载是经典的
template <typename T, typename U>
Matrix<T>& operator*(const Matrix<T>& a, const Matrix<U>& b)
{
assert(a.rows() == b.cols() && "You have to multiply a MxN matrix with a NxP one to get a MxP matrix\n");
Matrix<T> *c = new Matrix<T>(a.rows(), b.cols());
for (int ci=0 ; ci<c->rows() ; ++ci)
{
for (int cj=0 ; cj<c->cols() ; ++cj)
{
c->at(ci,cj)=0;
for (int k=0 ; k<a.cols() ; ++k)
{
c->at(ci,cj) += (T)(a.at(ci,k)*b.at(k,cj));
}
}
}
return *c;
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中,我返回一个与第一个参数相同类型的矩阵,即Matrix<int> * Matrix<float> = Matrix<int>.我的问题是如何才能检测出我所给出的两种最精确的类型,以便不会失去太多的精度,即拥有Matrix<int> * Matrix<float> = Matrix<float>?有聪明才能做到吗?
你需要的是只是当你乘一个出现这种情况的类型T由U.这可以通过以下方式给出:
template <class T, class U>
using product_type = decltype(std::declval<T>() * std::declval<U>());
Run Code Online (Sandbox Code Playgroud)
您可以将其用作额外的默认模板参数:
template <typename T, typename U, typename R = product_type<T, U>>
Matrix<R> operator*(const Matrix<T>& a, const Matrix<U>& b) {
...
}
Run Code Online (Sandbox Code Playgroud)
在C++ 03中,你可以通过执行一系列重载的大量重载来实现同样的功能(这就是Boost的工作方式):
template <int I> struct arith;
template <int I, typename T> struct arith_helper {
typedef T type;
typedef char (&result_type)[I];
};
template <> struct arith<1> : arith_helper<1, bool> { };
template <> struct arith<2> : arith_helper<2, bool> { };
template <> struct arith<3> : arith_helper<3, signed char> { };
template <> struct arith<4> : arith_helper<4, short> { };
// ... lots more
Run Code Online (Sandbox Code Playgroud)
然后我们可以写:
template <class T, class U>
class common_type {
private:
static arith<1>::result_type select(arith<1>::type );
static arith<2>::result_type select(arith<2>::type );
static arith<3>::result_type select(arith<3>::type );
// ...
static bool cond();
public:
typedef typename arith<sizeof(select(cond() ? T() : U() ))>::type type;
};
Run Code Online (Sandbox Code Playgroud)
假设你写出所有整数类型,那么你可以typename common_type<T, U>::type在我使用之前使用product_type.
如果这不是C++ 11有多酷的演示,我不知道是什么.
注意,operator* 不应该返回参考.你正在做什么会泄漏记忆.
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |