std::any_cast throws a bad any_cast error when converting void* to function pointer

  any, c++, dlopen

I wrote the code below,

std::unordered_map<std::string_view, std::any> symbols_;
symbols_["foo"] = dlsym(handle_), "foo");

When i use any_cast
return (std::any_cast<void(*)()>(symbols_["foo"]))();, the program will throw a error: bad any_cast.

I found the main reason because of the function .

template<typename _Tp>
void* __any_caster(const any* __any)

It would judge the condition as false and then return nullptr.

else if (__any->_M_manager == &any::_Manager<_Up>::_S_manage
#if __cpp_rtti
      || __any->type() == typeid(_Tp)
#endif
      ){
      any::_Arg __arg;
      __any->_M_manager(any::_Op_access, __any, &__arg);
      return __arg._M_obj;
}
return nullptr;

I want to know

1.why __any->_M_manager == &any::_Manager<_Up>::_S_manage and __any->type() == typeid(_Tp) were all false,

2.and how can i fix the problem(continue to use std::any).

Here is a simple demo.

#include <any>

void func() { }

auto main() -> int {
    std::any a = (void*)func;
    std::any_cast<void(*)()>(a)();
    return 1;
}

gcc version 10.1.0 (GCC)

Source: Windows Questions C++

LEAVE A COMMENT