r/cpp_questions • u/dvd0bvb • 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.
View all comments
Show parent comment
1
u/No-Dentist-1645 Feb 14 '26 edited Feb 14 '26
So, if I understand correctly, your main "issue" is that you don't want to fill up all your code with
Pipeline<Arg1, Arg2, ...>everywhere you use it, correct? You want the "usage" side code to be cleaner without template parameter ugliness.If so, there are better ways to do that.
Since C++17, you can use CTAD (Compile Time Argument Deduction) to deduce the template parameters. Using your same godbolt link, I changed the main() function to use A directly, no need for a Wrapper:
that works great, and you don't need to use
A<int, double, string>. Another thing you could do is ausingstatement:Finally, in case those still don't help your specific issue, the way to do what you originally wanted is to make the Wrapper's visit method be templated.
That way, you can have:
And at the usage side (i.e the "underlying Pipeline" you said already has the type information), there you'd pass the types:
Here's a godbolt link with your code modified to make it work: https://godbolt.org/z/6aTnzs5on . Personally, I'd recommend you use one of the first two approaches if your aim is just "ease of use for consumers" as another one of your comments says, but just for completion, the third method is your actual "answer" the way you wanted it.