【问题标题】:C++ - calling a method from a class templateC++ - 从类模板调用方法
【发布时间】:2011-05-18 05:34:12
【问题描述】:

我目前在使用 C++ 中的类模板时遇到问题。我目前正在制作一个哈希表。

我使用仿函数作为类模板来为表的每个实例指定我的哈希函数。

IE:一张表的键是整数,值是字符串。另一个可以有字符串作为它的键和整数作为它的值,等等......

class HashString
{
    public:
       unsigned long operator()(std::string& key, const unsigned int tableSize)
       {
           // .....
       }

};

template<typename keyType, typename valueType, class HashFunctor>
class HashTable
{
    public:
        // ....

    private:

        HashFunctor myHash;

};

现在假设我想调用名为“myHash”的方法来散列一个键,我首先会这样做:

myHash(key, table.size())

但是 gcc 没有找到例如 HashFuntor(string, unsigned int) 的函数重载。

有人能告诉我如何调用 myHash 吗? (注意:我不想改变我的函子结构)

编辑:这是我从实际解决方案中得到的错误消息

  instantiated from ‘void tp3::Table<TypeClef, TypeDonnee, FoncHachage>::insert(const TypeClef&, const TypeDonnee&) [with TypeClef = int, TypeDonnee = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, FoncHachage = tp3::HacheString]’

no match for call to ‘(tp3::HacheString) (tp3::Table<int, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, tp3::HacheString>::HashEntry&)’

编辑:到处都是 HacheString 实际上是 HashString(我已经翻译了我的代码以将其粘贴到此处)。

【问题讨论】:

  • 能贴出实际的错误和对应的代码吗?
  • @Alex 我上传了其中一条错误消息。他们都提到了同样的事情(因为我有我的电话)
  • boost::unordered_map 似乎是您想要的(您可以在 C++0x 中以 std::tr1::unordered_map 甚至 std::unordered_map 的形式访问它)。请不要重新发明轮子。
  • @Karl Knechtel 这只是为了教育目的。

标签: c++ templates class hashtable functor


【解决方案1】:
HashString 中的

operator() 是私有的,可能不是 const 正确的。它应该是一个以 const std::string& 作为其第一个参数的 const 成员函数。第二个参数不必是const。

您似乎使用 HashEntry 作为第二个参数来调用它。什么是HashEntry?它需要一个无符号整数!

这可能已经解决了你的一些问题。

我认为您的 HacheString / HashString 差异只是一个错字。

【讨论】:

  • 其实它是公开的,只是重新输入时出错,是的,绝对是 hash/hache 的错字(从法语到英语的翻译错字)
  • 其实HashEntry就是一个key/value的“节点”。我正在尝试通过散列其键来获取必须在表中插入 hashEntry 的表的位置。
猜你喜欢
  • 1970-01-01
  • 2015-02-25
  • 2013-03-07
  • 2016-08-17
  • 1970-01-01
  • 2011-10-22
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多