【问题标题】:C++ default copy/move assignment operator for extern C structure not const外部 C 结构的 C++ 默认复制/移动赋值运算符不是 const
【发布时间】:2015-04-28 13:02:48
【问题描述】:

我有一个std::map<CXCursor, DeclarationContent>,我想使用std::remove_if 从中删除元素。

CXCursor 是外部 C 代码 (libClang) 中的 (typedef of a) 结构,我不能/不得修改。

来自 clang++ 3.4.2 --std=c++11 的错误消息:

stl_pair.h:170:8: error: no viable overloaded '='
stl_algo.h:1152:23: note: in instantiation of member function std::pair<const CXCursor, DeclarationContent>::operator=' requested here

extract.cc:34:8: in instantiation of function template specialization 'std::remove_if<std::_Rb_tree_iterator<std::pair<const CXCursor, DeclarationContent> >, bool (*)(std::pair<const CXCursor, DeclarationContent> &)>' requested here
  std::remove_if(decls.begin(), decls.end(), noCodeGenerationRequested);

include/clang-c/Index.h:2137:9: note: candidate function (the implicit copy assignment operator) not viable:
  'this' argument has type 'const CXCursor', but method is not marked const

/include/clang-c/Index.h:2137:9: note: candidate function (the implicit move assignment operator) not viable:
  'this' argument has type 'const CXCursor', but method is not marked const

代码基本上是:

std::map<CXCursor, DeclarationContent> decls;
// filling the map
std::remove_if(decls.begin(), decls.end(), noCodeGenerationRequested);

bool noCodeGenerationRequested(std::map<CXCursor, DeclarationContent>::value_type & v)
{ /* FUN GOES HERE */ return true; }

从阅读错误消息来看,隐式赋值运算符似乎不是 const 限定的,这在映射的情况下是必需的(因为它的键始终是 const)。

我可以围绕 CXCursor 编写一个提供这些赋值运算符的包装类,但也许还有其他方法?


std::remove_if 不适用于std::map,请参阅:remove_if equivalent for std::map

【问题讨论】:

    标签: c++ c++11 stl constants assignment-operator


    【解决方案1】:

    map 不能与std::remove_if 一起使用,因为map::value_type 的类型为std::pair&lt;const T, U&gt;,但std::remove_if 要求,取消引用的迭代器应该是MoveAssignable。仅使用循环,或者可能在另一个容器中使用 copy_if 否定您的谓词。

    或者你可以使用boost::range::remove,如果你已经在你的项目中使用了 boost。

    【讨论】:

    • 哦..在阅读 remove_if 文档时一定错过了这一点。非常感谢,你让我免于编写一个无济于事的包装器。作为参考,我想我将使用此处介绍的 erase_if:stackoverflow.com/a/16597048/1116364
    猜你喜欢
    • 2013-08-09
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 2017-11-21
    相关资源
    最近更新 更多