如何在变体容器上使用stl算法

问题描述 投票:0回答:1

我有一个变种容器。有3种不同的类型共享相同接口的容器。我想用某些算法,例如find_if并累积。

    struct Type1{bool hasField(const string& name)const{return false;}};
    struct Type2{bool hasField(const string& name)const{return false;}};
    struct Type3{bool hasField(const string& name)const{return true;}};
    struct Type4{bool hasField(const string& name)const{return false;}}; 

    auto cont = vector<variant<Type1,Type2,Type3>>{Type1{},Type3{},Type2{}};

    string name{"field1"};

     //each type has hasField member.
    auto it = find_if(begin(cont), end(cont), [&name](const auto& field)
              {std::visit([](const auto& arg){return arg.hasField(name);}, field);});

      //another ex:

      return std::accumulate(begin(m_fields), end(m_fields), 0, 
           [](size_t tot, const auto& field){
              visit([&](const auto& f){return tot += f.getSize();}, field);});


          linux-gnu/include/c++/8.3.0/bits/predefined_ops.h:283:11: error: 
           void value not ignored as it ought to be
            { return bool(_M_pred(*__it)); }

有人可以告诉我正确的语法是什么吗?我尝试在Google周围搜索,但未找到任何示例。

c++ algorithm lambda c++17 variant
1个回答
0
投票

您的第一个例子就差不多了。 This compiles

auto it = find_if(
    begin(cont),
    end(cont),
    [&name](const auto& field) {
      return std::visit(
          [&name](const auto& arg){return arg.hasField(name);}, field
      );
    }
);
© www.soinside.com 2019 - 2024. All rights reserved.