最近在CentOS7上使用devtoolset-8的GCC编译代码出错,错误描述:
/opt/rh/devtoolset-8/root/usr/include/c++/8/bits/stl_set.h:133:17: required from ‘class std::set<std::weak_ptr<xxx:xxx>, xxx::xxx::SetCompare<xxx::xxx::xxx> >’
/home/sources/xxx/xxx.h:27:67: required from here
/opt/rh/devtoolset-8/root/usr/include/c++/8/bits/stl_tree.h:457:21: error: static assertion failed: comparison object must be invocable as const
static_assert(is_invocable_v<const _Compare&, const _Key&, const _Key&>,
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
原因:C++代码基于devtoolset-7的GCC版本7.3.1上编写的;devtoolset-8的GCC版本8.3.1上类set(见下面)的参数_Compare的语法做了改动,也就是说GCC版本7.3.1与GCC版本8.3.1的语法不同。
template<typename _Key, typename _Compare = std::less<_Key>,
typename _Alloc = std::allocator<_Key> >
class set
{
...
解决方法有两种;
1. 更换编译环境到devtoolset-7的GCC版本7.3.1
2. 修改代码,将类set的参数_Compare的传入参数XXX的申明进行调整,operator方法后面添加关键字const,见下面。
template<typename T>
struct XXX
{
bool operator() (const weak_ptr<T> &p1, const weak_ptr<T> &p2) const {
return (p1.lock < p2.lock);
}
};
注意:C++中类似的类方法的存在_Compare参数都存在此问题。