2

我有一个名为 Foo 的结构,其中包含一个函数,该函数调用它传递的任何方法并返回值。

struct Foo
{
    unsigned char fooFunc(unsigned char param, unsigned char(getValueMethod)(const unsigned char))
    {
        return getValueMethod(param);
    }
};

我有一个名为 barFunc 的方法...

static unsigned char barFunc(const unsigned char paramA)
{
    return paramA * 2;
}

...可以很好地传递给 fooFunc

Foo foo1;
foo1.fooFunc(10, &barFunc);

但我也希望 fooFunc 接受成员函数,比如 bazFunc ....

struct Baz
{
    unsigned char bazFunc(const unsigned char paramB)
    {
        return paramB * 3;
    }
};

……被这样称呼……

Foo foo2;
Baz baz;
foo2.fooFunc(10, ?????);

...但这是无效的。

我在将成员函数作为参数传递的主题上找到的所有内容都在谈论在调用对象之前知道对象来自哪个类,这意味着我必须创建 2 个函数而不是一个。

有没有一种我还没有找到的方法,它只需要 1 个 fooFunc 方法,但会支持非成员和成员函数?

4

3 回答 3

3

通过boost::function<signature>结果boost::bind()

bool free_func(std::string const& arg) { ... }

struct X {
    bool mem_func(std::string const& arg) { ... }
};

...
typedef boost::function<bool (std::string const& name)> func_t;

std::vector<func_t> funcs;
X x;

funcs.push_back(boost::bind(&X::mem_func, x, _1));
funcs.push_back(boost::bind(&free_func, _1));
于 2014-10-03T10:39:24.323 回答
1

使用 C++11 或提升您的任务很容易 - 但因为您想要 C++03 解决方案,然后按照评论中的建议 - 使用模板成员函数:

struct Foo
{
    template <typename Function>
    unsigned char fooFunc(unsigned char param, Function getValueMethod)
    {
        return getValueMethod(param);
    }
};

然后使用免费功能示例,您将不会更改任何内容:

Foo foo1;
foo1.fooFunc(10, &barFunc);

使用成员函数 - 只需使用 C++03std::mem_fun/bind1st中的 C++03 <functional>

#include <functional>
Foo foo2;
Baz baz;
foo2.fooFunc(10, std::bind1st(std::mem_fun(&Baz::bazFunc), &baz));
于 2014-10-03T10:47:57.320 回答
1

发布 c++11,根据其他答案

前 c++11:

#include <iostream>
#include <functional>


using namespace std;

struct foo_holder {

    template<class T>
    unsigned char foo(unsigned char v, T f) {
        return f(v);
    }

};

unsigned char bar(unsigned char param) {
    return param * 2;
}

struct baz {
    unsigned char bar(unsigned char param) {
        return param * 3;
    }
};

int main()
{
   cout << "Hello World" << endl; 

   foo_holder f;
   baz b;

   cout << static_cast<int>(
    f.foo(6, bar)
    ) << endl;

   cout << static_cast<int>(
    f.foo(6, std::bind1st(std::mem_fun(&baz::bar), &b))
    ) << endl;

   return 0;
}
于 2014-10-03T11:03:18.500 回答