【问题标题】:Use of C++ templates with dynamic binding class将 C++ 模板与动态绑定类一起使用
【发布时间】:2012-01-05 00:26:56
【问题描述】:

过去我在 C++ 中使用过模板和动态绑定,但最近我尝试将它们一起使用,发现无法编译。

我想做的是这样的:

     std::map<MyClass, unsigned int> mymap;

MyClass 恰好是一个利用动态内存绑定的类。经过几个小时的搜索后,我的印象是这会导致我仍然无法解决的问题,因此我希望就该问题以及如何解决该问题提供一些指导。

我的最终目标是能够做这样的事情:

std::vector<MyClass> MyClassPool;
//fill the vector with MyClass objects...
for(usigned int i=0 ; i<MyClassPool.size() ; i++)
{
    mymap[ MyClassPool[i] ] = i;
}

我尝试过以各种方式使用指针,但它不起作用,我看不到可以做什么。

我收到以下错误:

/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_function.h: In member function `bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Instance]':

/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_map.h:338:   instantiated from `_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = Instance, _Tp = float, _Compare = std::less<Instance>, _Alloc = std::allocator<std::pair<const Instance, float> >]'

/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_function.h:227: error: no match for 'operator<' in '__x < __y'

【问题讨论】:

  • “动态内存绑定”是什么意思?无论如何,您的代码看起来是正确的。你需要给我们MyClass的定义。
  • 你的意思不是vector 而不是Vector 吗?你使用的是标准的内置std :: vector,不是吗?
  • “它不起作用”是什么意思?你必须给我们更好的信息。它编译吗?您收到什么错误消息?
  • 奇怪的是,我收到了将我引导到库的编译错误。我将编辑原始问题以包含它们。是的,我正在使用标准的 std::vector

标签: c++ templates map dynamic-binding


【解决方案1】:

该编译错误意味着您没有为Instance 定义operator &lt;map 需要能够对键进行排序,需要这个功能。如果不想定义operator &lt;,则需要提供一个比较函数作为map的第三个模板参数,即std::map&lt;Instance, float, compare_instances&gt;

...想一想,您确定要将Instance 作为键,将float 作为数据,而不是相反? IE。您正在地图中搜索Instance 以获取float 作为回报?

【讨论】:

  • 是的,这是正确的,需要使用实例类作为键。
【解决方案2】:

您没有为MyClass 提供operator&lt;std::map 需要它。您有两个选择:提供一个比较器作为map 的第三个模板参数,或者在MyClass 中实现运算符。

【讨论】:

    【解决方案3】:

    这与“动态绑定”无关(无论如何,这不是这里的意思)。您的班级需要有一个订单才能放入地图。它需要运算符<.>

    【讨论】:

    • 在一次尝试中,我注意到一个错误,提到需要重载 operator
    • 只需将 bool MyClass::operator&lt;(MyClass const&amp; other){/*however you want to compare your classes*/} 写为 MyClass 类的方法。 “但是”部分由你决定,但它应该符合operator&lt; 的基本顺序要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    相关资源
    最近更新 更多