std::set使用自定义比较器时make_set_helper模板推导失败如何修复?
报错原因
std::set是包含3个模板参数的模板类,完整声明为template <class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key>> class set;,其中第二个参数是排序用的比较器,默认值为std::less<Key>。你当前的代码中set_helper和make_set_helper只捕获了第一个Key类型参数,默认固定了比较器为std::less<T>,因此传入自定义比较器(示例中为std::greater<int>)的std::set实例时,模板推导无法匹配,就会抛出类型不匹配的错误。- 你代码中的
operator==实现存在逻辑错误:直接将this指针和other值做比较,和“判断元素是否在set中”的预期逻辑完全不符。
修复方案
修改sethelp.h的代码如下:
#pragma once #include <set> // 模板参数和std::set保持对齐,支持自定义比较器、分配器 template<class Key, class Compare = std::less<Key>, class Alloc = std::allocator<Key>> class set_helper { private: std::set<Key, Compare, Alloc>* s; public: set_helper(std::set<Key, Compare, Alloc>& s) { this->s = &s; } // 修正operator==逻辑:判断other是否存在于set中 bool operator==(Key other) { return s->count(other) > 0; } std::set<Key, Compare, Alloc>* get_set() {return this->s;} }; // make_set_helper同步支持推导std::set的三个模板参数 template<class Key, class Compare, class Alloc> set_helper<Key, Compare, Alloc> make_set_helper(std::set<Key, Compare, Alloc>& s) { return set_helper<Key, Compare, Alloc>(s); }
修改后重新编译即可解决类型不匹配的报错,同时修正了比较运算符的逻辑问题。
内容的提问来源于stack exchange,提问作者devor110
相关产品推荐
相关产品推荐

