所以想象我们有2个功能(void : ( void ) ),(std::string : (int, std::string))而且我们还可以有10个功能.所有(或其中一些)采用不同的参数类型,并可以返回不同的类型.我们想将它们存储在a中std::map,因此我们得到这样的API:
//Having a functions like:
int hello_world(std::string name, const int & number )
{
name += "!";
std::cout << "Hello, " << name << std::endl;
return number;
}
//and
void i_do_shadowed_stuff()
{
return;
}
//We want to be capable to create a map (or some type with similar API) that would hold our functional objects. like so:
myMap.insert(std::pair<std::string, fun_object>("my_method_hello", hello_world) )
myMap.insert(std::pair<std::string, fun_object>("my_void_method", i_do_shadowed_stuff) )
//And we could call tham with params if needed:
int a = myMap["my_method_hello"]("Tim", 25);
myMap["my_void_method"];
Run Code Online (Sandbox Code Playgroud)
我想知道如何将许多不同的功能放入同一个容器中.具体来说,如何使用Boost在C++ 03中执行此操作.
API应该独立于实际的函数类型(int a = myMap["my_method_hello"]("Tim", 25);没有int a = myMap<int, (std::string, int)>["my_method_hello"]("Tim", 25);).
#include <functional>
#include <iostream>
#include <string>
#include <map>
class api {
// maps containing the different function pointers
typedef void(*voidfuncptr)();
typedef int(*stringcrintptr)(std::string, const int&);
std::map<std::string, voidfuncptr> voida;
std::map<std::string, stringcrintptr> stringcrint;
public:
// api temp class
// given an api and a name, it converts to a function pointer
// depending on parameters used
class apitemp {
const std::string n;
const api* p;
public:
apitemp(const std::string& name, const api* parent)
: n(name), p(parent) {}
operator voidfuncptr()
{ return p->voida.find(n)->second; }
operator stringcrintptr()
{ return p->stringcrint.find(n)->second; }
};
// insertion of new functions into appropriate maps
void insert(const std::string& name, voidfuncptr ptr)
{ voida[name]=ptr; }
void insert(const std::string& name, stringcrintptr ptr)
{ stringcrint[name]=ptr; }
// operator[] for the name gets halfway to the right function
apitemp operator[](std::string n) const
{ return apitemp(n, this); }
};
Run Code Online (Sandbox Code Playgroud)
用法:
api myMap;
int hello_world(std::string name, const int & number )
{
name += "!";
std::cout << "Hello, " << name << std::endl;
return number;
}
int main()
{
myMap.insert("my_method_hello", &hello_world );
int a = myMap["my_method_hello"]("Tim", 25);
}
Run Code Online (Sandbox Code Playgroud)
http://ideone.com/SXAPu 不是很漂亮.更好的建议是不要做任何事情,就像你正在尝试做的那样.
请注意,这要求具有相同参数的所有函数返回相同的类型.
| 归档时间: |
|
| 查看次数: |
4602 次 |
| 最近记录: |