Function using std::any and void*
11:06 02 Jan 2026

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:

  1. The fuction push should store pointers by type.
    • Tried use a set instead of list but had no success due to the std::any.
  2. The function get should grab pointers by its type.

I have some questions:

  1. Why pushWithVoid does not work as expected (REQUIRE(&a2 == b2) fails)?
  2. How can I change push to only accept pointers instead of std::any?
    • Should I use std::shared_ptr instead?
  3. Why I cannot separate in two files (header and impl) the get function?
    • When I do this, the compiler throws "main.cc:(.text+0x1580): undefined reference to `int* game::AsyncPointer::get()'", for example.
c++