为什么range-v3 yield需要默认构造函数

时间:2017-02-21 20:05:12

标签: c++ range-v3

我试图理解,为什么函数的yield系列要求该类是默认的可构造的?

在以下示例中,仅当CNum具有默认构造函数时,vnums1行才会编译。 vnums2行不需要默认构造函数。

我正在使用Visual Studio 2017和Range-V3-VS2015。谢谢!

#include <range/v3/all.hpp>

struct CNum
{
    // CNum() = default;
    explicit CNum(int num) : m_num(num) {}
    int m_num;
};

int main()
{
    auto ints = ranges::view::ints(0, 10);

    // this compiles only of CNum has a default constructor
    auto vnums1 = ints
        | ranges::view::for_each([](int num) { return ranges::yield_if(num % 2, CNum(num)); })
        | ranges::to_vector;

    // this compiles even if CNum does not have a default constructor
    auto vnums2 = ints
        | ranges::view::remove_if([](int num) { return num % 2 == 0; })
        | ranges::view::transform([](int num) { return CNum(num); })
        | ranges::to_vector;

    return 0;
}

2 个答案:

答案 0 :(得分:2)

我们刚刚将代码更改为不需要DefaultConstructible。 git pull and enjoy。

答案 1 :(得分:1)

您需要默认构造函数使用ranges::yield_if的原因是它使用的机制要求类型是默认构造的。如果我们查看我们的代码

struct yield_if_fn
{
    template<typename V>
    repeat_n_view<V> operator()(bool b, V v) const
    {
        return view::repeat_n(std::move(v), b ? 1 : 0);
    }
};

/// \relates yield_if_fn
/// \ingroup group-views
RANGES_INLINE_VARIABLE(yield_if_fn, yield_if)

我们可以看到它调用view::repeat_n。看看我们得到的代码

repeat_n_view<Val> operator()(Val value, std::ptrdiff_t n) const
{
    return repeat_n_view<Val>{std::move(value), n};
}

如果我们查看repeat_n_view我们有

// Ordinarily, a view shouldn't contain its elements. This is so that copying
// and assigning ranges is O(1), and also so that in the event of element
// mutation, all the copies of the range see the mutation the same way. The
// repeat_n_view *does* own its lone element, though. This is OK because:
//  - O(N) copying is fine when N==1 as it is in this case, and
//  - The element is immutable, so there is no potential for incorrect
//    semantics.

struct repeat_n_view
  : view_facade<repeat_n_view<Val>, finite>
{
private:
    friend range_access;
    Val value_;
    std::ptrdiff_t n_;

    // ...
public:
    repeat_n_view() = default;
    constexpr repeat_n_view(Val value, std::ptrdiff_t n)
      : value_(detail::move(value)), n_((RANGES_EXPECT(0 <= n), n))
    {}
    constexpr std::size_t size() const
    {
        return static_cast<std::size_t>(n_);
    }
};

我们从评论中看到这是一个设计决策,因为这个设计你需要你的类型是默认构造的。 Eric将所需的类型描述为SemiRegular,记录为

  

它需要是默认构造,复制和移动构造,以及可破坏。

相关问题