簡體   English   中英

如何在變體容器上使用 stl 算法

[英]how to use an stl algo on a container of variants

我有一個變體容器。 容器中有 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)); }

有人可以告訴我正確的語法是什么嗎? 我試着用谷歌搜索,但沒有找到任何例子。

你的第一個例子幾乎就在那里。 這編譯

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM