OiO.lk Blog templates Why does this function throw a “std::bad_any_cast”
templates

Why does this function throw a “std::bad_any_cast”


I am using C++ 17, the following code throws a std::bad_any_cast exception.
The message printed:

Current type in m_any: St8functionIFSt3anyP7ContextEE
Function type: St8functionIFSt3anyRP7ContextEE

The message indicates that m_any stores a type of Context*, yet when compute(Context*) is called, it treats context as Context*&.

template<typename Ret>
class AnyCallableF {
public:
    AnyCallableF() = default;

    template<typename F>
    AnyCallableF(F&& fun) : AnyCallableF(std::function(std::forward<F>(fun))) {}

    template<typename ... Args>
    AnyCallableF(std::function<Ret(Args...)> fun) : m_any(fun) {}

    template<typename ... Args>
    Ret operator()(Args&& ... args)
    {
        std::cout << "Current type in m_any: " << m_any.type().name() << endl;
        std::cout << "Function type: " << typeid(std::function<Ret(Args&&...)>).name() << endl;
        return std::invoke(std::any_cast<std::function<Ret(Args...)>&>(m_any), std::forward<Args>(args)...);
    }

private:
    std::any m_any;
};

struct Context {
    int a = 0;
};

std::any getValue(Context* ctx) {
    std::any v;
    return v;
}

void compute(Context* ctx) {
    std::unordered_map<std::string, AnyCallableF<std::any>> method_map;
    method_map["getValue"] = &getValue;
    std::any value = method_map["getValue"](ctx);
}

int main() {
    Context ctx;
    compute(&ctx);
}

However, when I modify the code as shown below, it executes successfully without errors.:

int main() {
    std::unordered_map<std::string, AnyCallableF<std::any>> method_map;
    method_map["getValue"] = &getValue;
    Context ctx;
    std::any value = method_map["getValue"](&ctx);
}

The message printed:

Current type in m_any: St8functionIFSt3anyP7ContextEE
Function type: St8functionIFSt3anyOP7ContextEE

Why they are different?



You need to sign in to view this answers

Exit mobile version