gpt4 book ai didi

c++ - boost::any 不能转换回 std::function

转载 作者:太空宇宙 更新时间:2023-11-03 10:25:28 27 4
gpt4 key购买 nike

我正在尝试将存储在 boost::any 中的函数指针转换回函数指针。

void foo(int, int) {}

template<typename T, typename... Ts>
void bar(T func, Ts... args)
{
boost::any any = func;

boost::any_cast<std::function<void(Ts...)>>(any)(args...);
}

但是 boost::any_cast 抛出一个 boost::bad_any_cast,但我不知道为什么,因为类型是相同的。

我调用bar如下

bar(foo, 0, 1);

我错过了什么吗?

最佳答案

当你回退 boost::any ,您必须转换回完全相同的类型。您不能存储 void (*)(int, int)并转换为 std::function<void(int, int)> .

您可以更改存储的内容或转换为的内容,以便它们匹配,它应该可以工作。

关于c++ - boost::any 不能转换回 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37058257/

27 4 0