Function using std::any and void*
Given the below code (running at https://godbolt.org/z/rEK1MEMxf):
#include "catch2/catch_all.hpp"
#include
#include
#include
#include
namespace AsyncPointer {
std::list pointers;
void push(const std::any &pointer) {
pointers.push_back(pointer);
}
void pushWithVoid(void *ptr) {
std::any pointer = ptr;
pointers.push_back(pointer);
}
template T *get() {
auto pointerIt = std::find_if(pointers.begin(), pointers.end(),
[](const std::any &ptr) {
return ptr.type() == typeid(T*);
});
if (pointerIt != pointers.end()) {
return std::any_cast(*pointerIt);
}
return nullptr;
}
}
TEST_CASE("Async-pointer should work properly", "[asyn-pointer]") {
int a0 = 0;
float a1 = 1.0;
double a2 = 2.0;
AsyncPointer::push(&a0);
AsyncPointer::push(&a1);
AsyncPointer::pushWithVoid(&a2);
int *b0 = AsyncPointer::get();
float *b1 = AsyncPointer::get();
double *b2 = AsyncPointer::get();
REQUIRE(&a0 == b0);
REQUIRE(&a1 == b1);
REQUIRE(&a2 == b2);
}
And given that the purposes are:
- The fuction
pushshould store pointers by type.- Tried use a
setinstead oflistbut had no success due to thestd::any.
- Tried use a
- The function
getshould grab pointers by its type.
I have some questions:
- Why
pushWithVoiddoes not work as expected(REQUIRE(&a2 == b2) fails)? - How can I change
pushto only accept pointers instead ofstd::any?- Should I use
std::shared_ptrinstead?
- Should I use
- Why I cannot separate in two files (header and impl) the
getfunction?- When I do this, the compiler throws "main.cc:(.text+0x1580): undefined reference to `int* game::AsyncPointer::get()'", for example.