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

5
这段代码为何这样操作?
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++的了解显然很有限,但我原本期望听到一声号角宣布多态骑士及其可靠的战马,但现在我只能听到一声马屁和一个悲伤的长号 :-(


3
因为太有趣了,点赞了。 :D - wilx
@wilx请不要嘲笑那些在类型错误上跌跌撞撞的新手。 - user1804599
4
@elyse:我觉得那不是最有趣的地方。是帖子中的最后一句话。 - wilx
2个回答

9

std::set 被声明为 如下所示:

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);

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接