Earlier I asked this question about std::variant
. Considering that the types hold by the variant are all printable by std::cout
, is there a simple way to implement a visitor?
Here for example, all the way down you have several lambdas to cover each type, but all do the same thing (except std::string
): std::cout << arg << ' ';
. Is there a way to not repeat my self?
std::visit(overloaded {
[](int arg) { std::cout << arg; },
[](long arg) { std::cout << arg; },
[](double arg) { std::cout << arg; }
// I removed the std::string case
}, v); // v is the std::variant
and write instead:
std::visit( [](auto arg) { std::cout << arg; }, v);
or something like:
template<typename T>
void printer(T arg) {std::cout << arg; }
//.......
std::visit(printer, v);