gpt4 book ai didi

c++ - 如何在映射中使用存储指向成员函数的指针的 Binder2nd 对象?

转载 作者:太空狗 更新时间:2023-10-29 21:29:13 28 4
gpt4 key购买 nike

我的问题类似于this one .我需要在映射中存储指向成员函数的指针。成员函数接受一个参数,该参数在构造映射时必须由特定值绑定(bind)。我怎么做? map 应该有一个 binder2nd 对象作为它的值。

例如:

enum { FOO, BAR };

exMap["foo"] = bind2nd(&classA::Func, FOO);

我不知道如何声明这张 map 。

最佳答案

这是一个使用 Boost.Function 的例子:

#include "boost/function.hpp"
#include <map>
#include <iostream>
#include <functional>

struct Foo {
void bar(int x) {
std::cout << "bar called with x=" << x << std::endl;
}
};

int main()
{
Foo foo;
std::map<int, boost::function<void (Foo*)> > m;

m[1] = std::bind2nd(std::mem_fun(&Foo::bar), 3);

m[1](&foo);

return 0;
}

显然这对于​​ binder2nd 是不可能的,因为它不是默认构造的,这是对 std::map 的值的要求。

由于您不能使用 Boost,您将不得不编写自己的 Binder 。

关于c++ - 如何在映射中使用存储指向成员函数的指针的 Binder2nd 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5389782/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com