What's wrong with std::valarray's operator*?

落爺英雄遲暮 提交于 2019-12-05 01:10:26

There is a trick called expression templates that permit efficiencies in compound expressions, but break horribly with use of auto.

Change this:

auto w = v * 2;

to this:

std::valarray<int> w = v * 2;

and your code works.


To see why we want to use expression templates, try this:

std::valarray<int> a={1,2,3},b{4,5,6},c={2,4,8};
std::valarray<int> r = (a+b*2)*c;

here the expression templates avoid creating a temporary valarray a+b*2 or b*2, but instead pass the entire expression down, and construct r with element-wise operations.

No 3-element valarray temporaries are created in (a+b*2)*c -- just a series of objects that describe the expression structure and arguments. When assigned to an actual valarray the expression is then evaluated on an element-by-element basis.

But auto doesn't convert to valarray; it just stores the expression template object. So your code breaks.

I don't know which versions of the standard permit this or not; regardless, some valarray implementations use this, and it adds a lot of efficiency. Without it, valarray frankly sucks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!