r/cpp_questions • • Feb 14 '26

SOLVED Visitor Pattern Using std::any

I'm attempting to write a type erased wrapper around a sort of tuple-like class. The wrapper holds a std::any where the tuple-ish class is stored. I want to implement a visit method where the wrapper takes some arbitrary callable which fills a similar role to std::apply. I can't seem to find a way to get the type of the object stored in the std::any in the same place as the function to apply.

I have a (hopefully) clarifying example here https://godbolt.org/z/xqd1q8sGc I would like to be able to remove the static_cast from line 47 as the types held in the tuple-like class are arbitrary.

I'm open to other ideas or approaches. The goal is to have a non-templated wrapper class for a container of unrelated types.

5 Upvotes

13 comments sorted by

View all comments

2

u/Business_Welcome_870 Feb 21 '26 edited Feb 25 '26

Okay, so after painstakingly working on this problem for the past 6 days, I was miraculously able to solve it. I took advantage of an ADL friend/deferred template instantiation trick. In the end we get a fairly clean solution: https://godbolt.org/z/bYcThr9xj

class Wrapper {
    struct type_tag {};

    template<class T>
    static constexpr auto inject_adl_definition() -> decltype(detail::Writer<type_tag, T>{}, void()) {}

    template<class F, class T>
    using variant_type = std::conditional_t<false, F, detail::Read<T>>;
public:
    template<class... Args, class V = A<Args...>>
    Wrapper(Args&&... args)
        : erased{ V{std::forward<Args>(args)...} }
    { inject_adl_definition<V*>(); }

    template<class F>
    void visit(F&& f) {
        std::any_cast<variant_type<F, type_tag>&>(erased).visit(std::forward<F>(f));
    }
private:
    std::any erased;
};

This works, but a big issue that this has is that the type_tag that is used to retrieve the tuple type is fixed for each instance of Wrapper. This means that if you create a second instance of Wrapper, it will retrieve the same A<Args...> type as the first wrapper. To get around this you will have to provide your own tag type. One way, which prevents Wrapper from being a template, is to accept the tag via the constructor and visit() parameters: https://godbolt.org/z/53fhGdvcY

struct first_tag {};
struct second_tag {};

Wrapper wrapper(first_tag{}, 9, 8.9, std::string("hello"));
Wrapper w2(second_tag{}, "abc"s,"spring"s);

wrapper.visit(first_tag{}, [](auto&& t) {
    std::println("{}", t);
});

w2.visit(second_tag{}, [](auto&& t) {
    std::println("Length of {} is {}", t, t.size());
});

If you don't want to manually create a new tag type and provide it every time you create an instance and call visit, the other option is to make Wrapper into a template that takes its tag by default parameter: https://godbolt.org/z/Ke1fMW7qa

template<class type_tag=decltype([]{})>
class Wrapper {
  ...
};

Wrapper wrapper(9, 8.9, std::string("hello"));

Now the tag will be unique for every instance of Wrapper. If at some point you need to create a function taking Wrapper as a parameter, it will need to be a function template:

template<class Tag>
void foo( Wrapper<Tag> );

This solution still erases the parameter pack, so I believe it should still be acceptable for you.

Let me know what you think.