【发布时间】:2013-02-07 16:09:43
【问题描述】:
我记得不久前读过一些代码,这些代码允许编译器完成一些工作并简化如下表达式:
// edit: yes the parameters where meant to be passed by reference
// and maintain constness sorry !
template< typename T >
std::vector<T> operator+( const std::vector<T>& a, const std::vector<T>& b )
{
assert( a.size() == b.size() );
std::vector<T> o; o.reserve( a.size() );
for( std::vector<T>::size_type i = 0; i < a.size(); ++i )
o[i] = a[i] + b[i];
return o;
}
// same for operator* but a[i] * b[i] instead
std::vector<double> a, b, c, d, e;
// do some initialization of the vectors
e = a * b + c * d
通常会为每个运算符创建和分配一个新向量,而编译器只会创建一个副本并对其执行所有操作。
这是什么技术?
【问题讨论】:
-
这里没有问题。
-
问题是……?还是您只是在寻找expression templates?
-
This question 可能是你第一次读到这个的地方。
-
返回值优化?
-
鉴于您的函数按值获取参数,
operator[]的成本将远低于函数调用本身的开销。
标签: c++ arrays performance operator-overloading hpc