6

Is there any inexpensive way to pass an arguments of non-variant types in addition to arguments of variant types, when multivisitor applyed?

What I mean by the term "expensive way" is:

#include <boost/variant.hpp>

#include <iostream>

#include <cstdlib>

struct A {};
struct B {};
enum class C { X, Y };

std::ostream &
operator << (std::ostream & out, C const c)
{
    switch (c) {
        case C::X : {
            return out << "C::X";
        }
        case C::Y : {
            return out << "C::Y";
        }
        default : {
            break;
        }
    }
    throw std::runtime_error("unknown C value");
}

using V = boost::variant< A, B >;

struct S
    : boost::static_visitor<>
{

    void
    operator () (C const c, A const &) const
    {
        std::cout << c << " A" << std::endl;
    }

    void
    operator () (C const c, B const &) const
    {
        std::cout << c << " B" << std::endl;
    }

};

int main()
{
    V const a = A{};
    V const b = B{};
    using VC = boost::variant< C >;
    VC const x = C::X;
    VC const y = C::Y;
    S const s;
    boost::apply_visitor(s, x, a);
    boost::apply_visitor(s, y, a);
    boost::apply_visitor(s, x, b);
    boost::apply_visitor(s, y, b);
    return EXIT_SUCCESS;
}

Another expensive way is to make non-static visitor with fileds of required types (or references to required types) and construct instances of such visitor for each set of values of non-variant types every time.

Tomilov Anatoliy
  • 15,657
  • 10
  • 64
  • 169
  • How would you like the API to be? Could you give a sample how you would like to use it? – Mike M Mar 16 '14 at 15:37
  • Something like `boost::apply_visitor(v, make_non_variant(C::X), a)`. Where `make_non_variant` is the function template, which allow to pass an argument as reference to visitor (by means of wrapping into some `non_variant_wrapper< C >` type instance). – Tomilov Anatoliy Mar 27 '14 at 16:35
  • I'd also love that! Did you learn anything new on this subject? – Dimitri Schachmann Jul 16 '15 at 09:45
  • 1
    @DimitriSchachmann I invent and use my own multivisitor https://github.com/tomilov/variant/blob/master/include/versatile/versatile/visit.hpp#L145 . It is not too hard to adapt it to be compatible with `boost::variant`: just change implementation, or add specialisation for `is_variant` type trait. – Tomilov Anatoliy Jul 16 '15 at 13:20

0 Answers0