2014-10-03 30 views
2

我有一个结构称为富其中包含调用任何方法将其传递和返回值的函数。通个人会员和非成员函数指针作为参数

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的方法,但将支持非成员和成员函数?

+0

你可以使用C++ 11? – 2014-10-03 10:14:15

+1

不,我不能..... – Beakie 2014-10-03 10:14:30

+0

你想'的boost :: bind'(绑定了'this'指针)和模板可调用。从技术上讲,这将导致多个'fooFunc '---方法---成员函数,但只有一个'fooFunc'成员函数模板! – 2014-10-03 10:15:27

回答

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; 
} 
+0

因为我的代码不是C++ 11,而且我不想实现boost,所以我会将其作为我的答案(即使我不想创建2个函数,即使使用模板),因为它是我实际实施的最佳工作解决方案。 – Beakie 2014-10-03 11:13:42

+0

只有一个'foo_holder :: foo'的定义 - 相当于你的'Foo :: fooFunc'。只是它是一个模板成员函数。 – 2014-10-03 11:19:54

+0

但是如果我用2个调用实现它,一个使用成员函数,另一个使用非成员函数,我会得到2个(编译)函数,对吧? – Beakie 2014-10-03 11:29:28

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)); 
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++从C++ 03 :

#include <functional> 
Foo foo2; 
Baz baz; 
foo2.fooFunc(10, std::bind1st(std::mem_fun(&Baz::bazFunc), &baz));