C++11 std::map 程序无法在 clang 3.4 中编译

A C++11 std::map program can't be compiled in clang 3.4

本文关键字:clang 编译 std map 程序 C++11      更新时间:2023-10-16

我是c++新手。我试图在clang 3.4中编译一个非常简单的std::map程序,带有"-std=c++11 -stdlib=libc++"标志,我得到了我不理解的错误。

#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()的第三行,只是不明白为什么。同样的程序在g++ 4.8.2中使用"-std=c++11"标志也很好,我相信它在VC2010中也很好。

谢谢。

您的operator()成员必须是const:

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