std::any bad cast whenever a function inside a header is implemented in a cpp file returns it

224 views Asked by At

This is my main.cpp


#include <iostream>
#include <unordered_map>
#include <string>
#include "myclass.h"

int main(int argc, const char * argv[]) {
    any a = myclass::returnthis();
    unordered_map<string, any>* hmap = any_cast<unordered_map<string, any>*>(a);
    return 0;
}


this is myclass.h

#ifndef myclass_h
#define myclass_h

#include <any>

using namespace std;

class myclass {
public:
    static any returnthis();
};

#endif /* myclass_h */

and this is myclass.cpp

#include "myclass.h"
#include <any>
#include <unordered_map>
#include <string>

any myclass::returnthis() {
    return new unordered_map<string, any>();
}

Now, any_cast will report bad any cast. I am working on macOS and I have tried Xcode and CLion. However, if I put the implementation of the function inside the header file, the problem vanishes. Why?

0

There are 0 answers