set <T> 与 set <T, comparator>(C++ 多态性)

set <T> vs set <T, comparator> (C++ polymorphism)

为什么这个代码

struct ThingComparator
{
    ...
}

static void Blah (set <CString> &things)
{
    ...
}

...

set<CString, ThingComparator>things;
Blah (things);

编译失败,出现以下错误 (Visual Studio 2010):

error C2664: 'Blah' : cannot convert parameter 1 from 'std::set<_Kty,_Pr>' to 'std::set<_Kty> &'

我的 C++ 知识显然是有限的,但我希望听到喇叭声宣布多态骑士骑在他可信赖的骏马上,但我听到的只是马屁和悲伤的长号:-(

std::set 声明为 as follows:

template<
    class Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class set;

因此 std::set<CString> 真正意味着 std::set<CString, std::less<CString>, std::allocator<CString>>,而 std::less<CString> 不是 ThingComparator。改写以下内容:

struct ThingComparator {
    ...
};

template<typename Comparator>
static void Blah(std::set<CString, Comparator>& things) {
    ...
}

...

std::set<CString, ThingComparator> things;
Blah(things);

所涉及的多态性不是运行时多态性,这在您的情况下是必需的。该函数应成为模板或 std::set<CString, std::function<bool(const CString&, const CString&)>> 以在比较器上显式调用运行时多态性。