【问题标题】:A C++11 std::map program can't be compiled in clang 3.4C++11 std::map 程序无法在 clang 3.4 中编译
【发布时间】:2014-05-12 09:11:30
【问题描述】:

我是 C++ 新手。我尝试在 clang 3.4 中使用“-std=c++11 -stdlib=libc++”标志编译一个非常简单的 std::map progeam,但出现了我不理解的错误。

#include<map>
#include<string>

template<typename KeyType>
struct ReverseSort {
    bool operator() (const KeyType& key1, const KeyType& key2) {
        return (key1 > key2);
    }
};

int main() {
    using namespace std;
    map<int, string> mapIntToString1;
    map<int, string, ReverseSort<int> > mapIntToString4(mapIntToString1.cbegin(), mapIntToString1.cend());

    return 0;
}

错误是:

map:457:17: error: no matching function for call to object of type 'const ReverseSort<int>'

我知道错误来自 main() 中的第 3 行,只是不明白为什么。 相同的程序在带有“-std=c++11”标志的 g++ 4.8.2 中很好,我相信在 VC2010 中也很好。

谢谢。

【问题讨论】:

  • 为什么不直接使用std::greater&lt;int&gt;?!
  • 究竟是什么VC2010
  • @Jagannath 你的评论太离谱了。这是一个完全有效的问题。

标签: c++ c++11 clang clang++


【解决方案1】:

您的operator() 成员必须是const

bool operator() (const KeyType& key1, const KeyType& key2) const
{   //                                                     ^^^^^
    return (key1 > key2);
}

【讨论】:

  • 请注意,GCC 4.9 的 libstdc++ 和 MSVS2013 都不会“捕捉”这一点。
  • @rubenvb 我不认为这是标准要求的。
  • @juanchopanza: 如果你查看23.4.4.1 (n3337 p763) 中的value_compare 类,它的operator()const,这使得Compare 对象const 在其中函数的上下文,因此它的operator() 也必须是const,对吗?还是我读错了?不确定这在多大程度上转化为需求...
  • 现在我可以用“const”编译它了
  • @Stephen:是的,我也希望如此。但是不要重新发明所有这些轮子并使用std::greater&lt;int&gt;
猜你喜欢
  • 1970-01-01
  • 2014-06-21
  • 2021-04-29
  • 2018-09-12
  • 1970-01-01
  • 2012-10-18
  • 2020-08-29
  • 2014-04-02
  • 2013-08-20
相关资源
最近更新 更多