Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

请问map<string, any>怎么存取function<>呢?

#include <map>
#include <iostream>
#include <any>
#include <functional>

using namespace std;

int add(int a, int b) {
    return a + b;
}

void echo(string s) {
    cout << s << endl;
}

int main() {
    map<string, any> mp;
    mp["add"] = add;
    mp["echo"] = echo;

    auto f = any_cast<function<void(string)>>(mp["echo"]);
    auto f = mp["echo"];
    f("hello");
}

这是我现在的代码,但是都是错的,想写个rpc的函数注册但是卡在了泛型这里,如果不能用any的话有什么其他办法么?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

两个 auto f 是认真的吗?

这样写是可以运行的

mp["add"]  = add;
mp["echo"] = echo;

mp["f_add"]  = function<int(int, int)>( add );
mp["f_echo"] = function<void(string)>( echo );

auto f_echo_fun = any_cast<function<void(string)>>( mp["f_echo"] );
auto echo_fun   = any_cast<void(*)(string)>( mp["echo"] );

f_echo_fun( "hello" );
echo_fun( "hello" );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...