gpt4 book ai didi

c++ - 如何将 "const void*"转换为 C++11 中的函数指针?

转载 作者:行者123 更新时间:2023-12-02 00:03:21 26 4
gpt4 key购买 nike

我想将一些 const void* 对象转换为函数指针:

std::unordered_map<std::string, const void*> originals_;

template <typename R, typename... Args>
R CallOriginal(const std::string& name, Args... args) {
return reinterpret_cast<R (*const)(Args...)>(originals_[name])(args...);
}

但是,令我惊讶的是,我收到以下错误消息:

error: reinterpret_cast from 'mapped_type' (aka 'const void *') to 'int (*const)(int)' casts away qualifiers

首先,使用 const 函数指针是否有意义?如果是的话,我怎样才能合法地进行选角?

最佳答案

为了通过名称调用任何函数,您可以使用 std::any与标准库仿函数结合std::function

请注意,调用者必须知道签名,例如无法推断参数类型和返回类型。

一个例子:

#include <any>
#include <functional>
#include <string>
#include <unordered_map>

#include <iostream>

static int foo(int a, const std::string& b) {
std::cout << "foo(" << a << ',' << b << ");" << std::endl;
return 0;
}

static void bar(float a, const std::string& b) {
std::cout << "bar(" << a << ',' << b << ");" << std::endl;
}

class call_function_by_name {
public:
explicit call_function_by_name(std::unordered_map<std::string, std::any>&& table):
table_(table)
{}
template <typename R,typename... ArgTypes>
R call(const std::string& name,ArgTypes... args) const {
typedef std::function<R(ArgTypes...)> functor_t;
std::any anyf = table_.at(name);
// call function by name
functor_t functor = std::any_cast<functor_t>( anyf ) ;
return functor( args... );
}
private:
std::unordered_map<std::string, std::any> table_;
};


int main(int argc, const char** argv)
{

std::unordered_map<std::string, std::any> exportTable;
exportTable.emplace("foo", std::function<int(int,const std::string&)>(foo) );
exportTable.emplace("bar", std::function<void(float,const std::string&)>(bar) );

call_function_by_name bus( std::move(exportTable) );
int ret = bus.call<int,int,const std::string&>("foo", 1, std::string("bus foo") );
std::cout << "Foo returned " << ret << std::endl;
bus.call<void,float,const std::string&>("bar", 2.0F, "bus bar");

return 0;
}

关于c++ - 如何将 "const void*"转换为 C++11 中的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28524179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com