boost::variant and a general, generic visitor class

Starting a new project with boost::variant, I got into thinking about a general generic visitor for boost::variant...

boost::variant and a general, generic visitor class

by Jens Weller

From the article:

So, I started a new project, and I do use boost::variant to be able to stick otherwise unrelated classes into the same container. Actually a tree, but that doesn't matter here. With boost::variant, you simply derive your visitor class from the static_visitor class, which lets you visit the types in a boost::variant via the call operator. When you want to do always the same for all types, you simply can add a template method version of the call operator...

Add a Comment

Comments are closed.

Comments (3)

1 0

Ivan Le Lann said on Jul 28, 2015 01:44 PM:

"a late binding method pointer, which it self isn't possible in C++, as its impossible to obtain a pointer to a method of a yet unknown type"

But can't you give your visitor an indirection layer eventually pointing to the member you want ?
template <typename T> struct name_member { static constexpr auto value = &T::name;};


http://coliru.stacked-crooked.com/a/744d4c40efda5581

1 0

Yakk said on Jul 28, 2015 05:44 PM:

Instead of a class, have a function.

It takes a variant and a lambda. It creates a visitor returning
std::common_type_t<std::result_of_t<lambda(Ts&)>...>
if it exists, and void otherwise.

It then uses that visitor on the variant, and returns what it returns.

0 0

M2tM said on Jul 30, 2015 10:55 AM:

I got downvoted on StackOverflow for this question, but I want to share my own solution to a generic visitor pattern: http://stackoverflow.com/questions/30600763/variadic-visitor-type-deduction

It allows you to call a matching function signature on a collection of objects based on their type.