所以,用下面的代码,改变参数的类型x从const ull到const ull&(有typedef unsigned long long ull)在约25%的加速效果,当用gcc 4.7.2和标志编译-O3 -std=c++11 -g,我想不通为什么会做出如此大的差异.
static void inline single_mult(const std::vector<ull>::iterator& data,
const std::vector<ull>::const_iterator& rbegin,
const std::vector<ull>::const_iterator& rend,
const ull x) {
ull tmp=0, carry=0, i=0;
for (auto rhs_it = rbegin; rhs_it != rend; ++rhs_it) {
tmp = x*(*rhs_it) + data[i] + carry;
if (tmp >= imax) {
carry = tmp >> numbits;
tmp &= imax - 1;
} else {
carry = 0;
}
data[i++] …Run Code Online (Sandbox Code Playgroud) 我想写一个模板函数
template <typename T>
void f( T v );
Run Code Online (Sandbox Code Playgroud)
v如果它足够小,将通过值传递,否则通过引用到const传递.为此,我使用了一个小帮手
template <typename T, bool>
struct parameter_helper;
template <typename T>
struct parameter_helper<T, true> {
typedef T type;
};
template <typename T>
struct parameter_helper<T, false> {
typedef const T& type;
};
template <typename T>
struct parameter {
typedef typename parameter_helper<T, sizeof(T) <= sizeof(void*)>::type type;
};
Run Code Online (Sandbox Code Playgroud)
在过去,我可以拥有
template <typename T>
void f( typename parameter<T>::type v );
Run Code Online (Sandbox Code Playgroud)
现在,在C++ 11中:这种辅助模板是否仍然有意义,还是有更好的方法来实现相同的效果?可能已经有现成的模板吗?我检查过<type_traits>但无法发现任何看似相关的东西.
我想知道为什么在STL中的许多模板算法中,参数不是通过引用传递的,而是通过值传递的.以下是<iterator>标题中的示例:
template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance (InputIterator first, InputIterator last);
Run Code Online (Sandbox Code Playgroud)
当我将两个迭代器传递给此函数时,它们将被复制.我天真的想法是,最好通过const-reference传递这些迭代器,以避免复制迭代器对象:
template<class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance (const InputIterator &first, const InputIterator &last);
Run Code Online (Sandbox Code Playgroud)
可以说迭代器通常是非常小的对象,复制它们并不昂贵.但即便如此:便宜的复制将比没有复制更昂贵.
那么在STL版本中,迭代器是按值传递的原因是什么?
谢谢!