首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用<functional>和<bind>的错误<bind>

使用<functional>和<bind>的错误<bind>
EN

Stack Overflow用户
提问于 2013-11-09 19:57:07
回答 2查看 1.6K关注 0票数 0

我真的不知道在这里该怎么办。我查到的每一个答案都有我不明白的语法。

错误:

代码语言:javascript
复制
Error 1 error C2064: term does not evaluate to a function taking 1 arguments

我在哈希表构造函数中使用函数指针。有人建议我使用和头来解决我正在处理的一个问题。它解决了错误,但我遇到了上面的错误。

我的Hash表声明和ctor如下:

代码语言:javascript
复制
#pragma once
#include "SLList.h"

template<typename Type> class HTable
{
public:
     HTable(unsigned int numOfBuckets, std::function<unsigned int(const Type&)>           hFunction);
    ~HTable();
    HTable<Type>& operator=(const HTable<Type>& that);
    HTable(const HTable<Type>& that);
    void insert(const Type& v);
    bool findAndRemove(const Type& v);
    void clear();
    int find(const Type& v) const;

private:
    SLList<Type>* ht;
    std::function<unsigned int(const Type&)> hFunct;
    unsigned int numOfBuck;
}; 

template<typename Type>
HTable<Type>:: HTable(unsigned int numOfBuckets, std::function<unsigned int(const     Type&)> hFunction)
{
    ht = new SLList<Type>[numOfBuckets];
    this->numOfBuck = numOfBuckets;
    this->hFunct = hFunction;
} 

Game.h (包含表):

代码语言:javascript
复制
#pragma once

#include "stdafx.h"
#include "HTable.h"
#include "BST.h"
#include "DTSTimer.h"

using namespace std;

class Game
{
public:
    Game(void);
    virtual ~Game(void);
    void refresh();
    void input();
    unsigned int xorHash(const string &s);

private:
    string userInput;
    DTSTimer timer;
    BST<string> answers;
    HTable<string> dictionary;
}; 

Game.cpp (我试图传递xorHash函数)

代码语言:javascript
复制
#include "Game.h"


Game::Game(void) : dictionary(2048, std::bind(&Game::xorHash, this))
{

}


Game::~Game(void)
{

}

void Game::refresh()
{

}

void Game::input()
{

}

unsigned int Game::xorHash(const string &s)
{
    return 0;
}

提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-09 20:03:35

您需要一个未绑定函数参数的占位符:

代码语言:javascript
复制
std::bind(&Game::xorHash, this, std::placeholders::_1)

根据口味,朗姆达可能更具可读性:

代码语言:javascript
复制
[this](const std::string & s){return xorHash(s);}

虽然我不清楚为什么xorHash需要成为非静态成员;当然,散列应该只依赖于它的输入?

票数 0
EN

Stack Overflow用户

发布于 2013-11-09 20:02:27

您要传递的散列函数对象仍然需要以哈希值作为参数。也就是说你想要绑定类似的东西

代码语言:javascript
复制
std::bind(&Game::xorHash, this, std::placeholders::_1)

需要使用_1-bit来告诉std::bind(),一个参数必须去哪里,哪个参数要发送到那里(在这个上下文中哪一个不那么有趣,因为只有一个;如果要绑定要接收多个参数的函数,则更有趣)。

注意,实际上不太可能要传递一个真正的成员函数:通常,计算出来的哈希值不依赖于对象状态,也就是说,最好是将xorHash()作为类的static成员函数,然后传入这个函数:这样甚至不需要std::bind()任何参数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19882364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档