【问题标题】:set <T> vs set <T, comparator> (C++ polymorphism)设置 <T> 与设置 <T,比较器>(C++ 多态性)
【发布时间】:2015-08-09 20:47:11
【问题描述】:

为什么会有这段代码

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++ 知识显然是有限的,但我希望听到一个小号宣布多态骑士骑在他可信赖的骏马上,但我只能听到马屁和悲伤的长号:-(

【问题讨论】:

  • 为欢闹而投票。 :D
  • @wilx 请不要嘲笑遇到类型错误的新手。
  • @elyse:这不是我觉得好笑的地方。这是帖子的最后一句话。

标签: c++ stl set polymorphism


【解决方案1】:

std::set 被声明为as follows

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

因此std::set&lt;CString&gt; 真正的意思是std::set&lt;CString, std::less&lt;CString&gt;, std::allocator&lt;CString&gt;&gt;,而std::less&lt;CString&gt; 不是ThingComparator。请改写以下内容:

struct ThingComparator {
    ...
};

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

...

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      相关资源
      最近更新 更多