MSVC++2022中C4180 const警告是否属于误报?
关于MSVC函数类型const限定警告的问题分析
相关代码
#include <algorithm> #include <vector> bool MyComparator(const int lhs, const int rhs) { // 此处包含更多逻辑 return lhs < rhs; } template <typename T, typename Comp = std::less<T>> class seq_forward_comparator { const std::vector<T>& vec; const Comp& comp; public: static const std::size_t npos = ((std::size_t)-1); seq_forward_comparator(const std::vector<T>& vec, const Comp& comp = {}) : vec(vec), comp(comp) { } bool operator() (int idx1, int idx2) { // 此处包含更多逻辑 return std::ranges::lexicographical_compare(vec.begin()+idx1,vec.end(), vec.begin() + idx2, vec.end(), comp); } }; int main() { std::vector<int> vec = { 1, 2, 3, 4 }; seq_forward_comparator<int, decltype(MyComparator)> less2(vec, MyComparator); seq_forward_comparator<int> less1(vec); }
编译警告情况
使用MSVC编译上述代码时,会触发以下警告:
<source>(13): warning C4180: qualifier applied to function type has no meaning; ignored <source>(13): note: the template instantiation context (the oldest one first) is <source>(29): note: see reference to class template instantiation 'seq_forward_comparator<int,bool (int,int)>' being compiled <source>(17): warning C4180: qualifier applied to function type has no meaning; ignored
而使用Clang编译时则不会产生该警告。
临时修改尝试
若将代码中:
seq_forward_comparator<int, decltype(MyComparator)> less2(vec, MyComparator);
替换为:
seq_forward_comparator<int, decltype(MyComparator)*> less2(vec, MyComparator);
MSVC 2022将不再产生警告,但该方案存在问题——必须严格按照函数指针类型传递谓词。
核心疑问
- 该警告是否属于误报?
- 若不是误报,除了提示“多余的
const限定”之外,还预示着哪些潜在问题?为何将类型从函数类型(本质会退化为函数指针)改为显式函数指针就能解决警告? - 若是误报,除了抑制警告和传递显式函数指针外,最佳的规避方式是什么?
内容的提问来源于stack exchange,提问作者Damir Tenishev
相关产品推荐
相关产品推荐

