简体   繁体   English

它是在 gcc 中实现 std::valarray 的错误吗?

[英]Is it a bug of the implementation of std::valarray in gcc?

I tried the following program我尝试了以下程序

#include <iostream>
#include <valarray>

int main( void ) 
{
    std::valarray<int> v1 = { 1, 2, 3, 4, 5 };
    std::valarray<int> v2 = { 1, 2, 3, 4, 5 };

    auto v3 = v1 * v2;

    for ( const auto &item : v3 ) std::cout << item << ' ';
    std::cout << '\n';

    return 0;
}

and got an error message that an appropriate function begin for v3 used implicitly in this statement并收到一条错误消息,指出在此语句中隐式使用了适用于v3的 function begin

    for ( const auto &item : v3 ) std::cout << item << ' ';

can not be found.找不到。

So I tried the following code所以我尝试了以下代码

#include <iostream>
#include <valarray>
#include <type_traits>

int main( void ) 
{
    std::valarray<int> v1 = { 1, 2, 3, 4, 5 };
    std::valarray<int> v2 = { 1, 2, 3, 4, 5 };

    auto v3 = v1 * v2;

    std::cout << std::is_same<std::valarray<int>, decltype( v3 )>::value << '\n';
    return 0;
}

and got the result并得到了结果

0

But when this statement但是当这句话

auto v3 = v1 * v2;

is changed to改为

std::valarray<int> v3 = v1 * v2;

then the output is那么 output 是

1

The operator * for std::valarray<int> is declared the following way std::valarray<int>operator *声明如下

template<class T> valarray<T> operator* (const valarray<T>&, const valarray<T>&);

So is it a bug of the implementation of std::valarray<int> ?那么它是std::valarray<int>实现的错误吗?

This is not a bug.这不是错误。 std::valarray::operator* does not actually have to return a std::valarray because it is allowed to use expression templates. std::valarray::operator*实际上不必返回std::valarray ,因为它允许使用表达式模板。 That means it can return a type that has the following properties:这意味着它可以返回具有以下属性的类型:

  • All const member functions of std::valarray are provided.提供了std::valarray的所有 const 成员函数。
  • std::valarray , std::slice_array , std::gslice_array , std::mask_array and std::indirect_array can be constructed from the replacement type. std::valarraystd::slice_arraystd::gslice_arraystd::mask_arraystd::indirect_array可以从替换类型构造。
  • All functions accepting an argument of type const std::valarray& except begin() and end() (since C++11) should also accept the replacement type .所有接受const std::valarray&类型参数的函数除了begin()end() (C++11 起) 也应该接受替换类型
  • All functions accepting two arguments of type const std::valarray& should accept every combination of const std::valarray& and the replacement type.所有接受两个const std::valarray&类型的 arguments 的函数都应该接受const std::valarray&和替换类型的每个组合。
  • The return type does not add more than two levels of template nesting over the most deeply-nested argument type.返回类型不会在嵌套最深的参数类型上添加超过两层的模板嵌套。

emphasis mine source强调矿

Because of this, you need to explicitly capture the return as a std::valarray so the specialization for std::begin can be called.因此,您需要将返回显式捕获为std::valarray以便可以调用std::begin的特化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM