Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 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 Answer

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" );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...