13

I need to fill in some template magic to make the following code snippet to work.

The problem is that I want to be able to define a visitor class for std::variant with named static methods accepting two arguments. How can I fill in Applicator::apply() to make the dispatching work?

struct EventA {};

struct EventB {};

struct EventC {};

using Event = std::variant<EventA, EventB, EventC>;

struct Visitor {
  enum class LastEvent { None, A, B, C };

  struct State {
    LastEvent last_event = LastEvent::None;
  };

  static State apply(State s, EventA e) { return State{LastEvent::A}; }

  static State apply(State s, EventB e) { return State{LastEvent::B}; }
};

template <typename Visitor> struct Applicator {

  static State apply(State s, Event e) {

    /*** Start of pseudo code ***/
    if (Visitor can apply) {
      return Visitor::apply(s, e);
    }
    /*** End of pseudo code ***/

    // Else, don't update state state
    return s;
  }
};

int main() {
  // Handled by visitor
  State s1 = Applicator<Visitor>::apply(State{}, EventA{});
  assert(s1.last_event == Visitor::LastEvent::A);

  // Handled by visitor
  State s2 = Applicator<Visitor>::apply(State{}, EventB{});
  assert(s2.last_event == Visitor::LastEvent::B);

  // NOT handled by visitor
  State s3 = Applicator<Visitor>::apply(State{}, EventC{});
  assert(s3.last_event == Visitor::LastEvent::None);
}
4
  • 1
    Aside: is State really meant to be a member of Visitor?
    – Caleth
    Jan 4, 2019 at 11:12
  • @Caleth yes, the Visitor is just used as a namespace to handle different kinds of events so it should encapsulate both the state and the operations that operates on that state. This is a very contrived example though. Jan 4, 2019 at 11:28
  • 2
    then it should be typename Visitor::State in Applicator (or Visitor::State if you drop the template parameter that shadows the class)
    – Caleth
    Jan 4, 2019 at 11:31
  • Well I didn't try compiling it since it contains pseudo code, as I said - it is a contrived example. Jan 4, 2019 at 12:47

4 Answers 4

7

Another solution:

using State = Visitor::State;

template<class Visitor>
struct VisitorProxy {
    State s;

    template<class E>
    auto operator()(E const& e) -> decltype(Visitor::apply(s, e)) {
        return Visitor::apply(s, e);
    }

    template<class E>
    State operator()(E const&) const {
        return s;
    }
};

template <typename Visitor> struct Applicator {
    static State apply(State s, Event e) {
        VisitorProxy<Visitor> p{s};
        return std::visit(p, e);
    }
};
2
  • 2
    Priorizing on const... Now that's a clever trick I didn't see before. Neat!
    – Quentin
    Jan 4, 2019 at 10:42
  • 1
    Thank you! This worked perfectly. I didn't know you could do SFINAE on the return type like that :) Jan 4, 2019 at 11:26
5

Using the now quite common overloaded class template trick (And Maxim's trick to order the lambdas based on the constness of their operator()) to create a SFINAE-capable functor modeling the logic you're lookig for:

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

// ...

template <typename Visitor> struct Applicator {
  static typename Visitor::State apply(typename Visitor::State s, Event e) {
    return std::visit(overloaded{
      [&s](auto e) mutable -> decltype(Visitor::apply(s, e)) { return Visitor::apply(s, e); },
      [&s](auto) { return s; }
    }, e);
  }
};

Note that this ICEs all versions of Clang I've tested on Wandbox, but I haven't found a workaround. Perfect forwarding is left as an exercise to the reader :)

4
  • 1
    Is it not UB to pass Event into ...? Jan 4, 2019 at 10:42
  • 1
    @MaximEgorushkin I thought it was okay, but apparently it is implementation-defined... I'll pinch your const-based ordering instead, much safer ;)
    – Quentin
    Jan 4, 2019 at 10:45
  • Why is it implementation defined to pass Event into ...?
    – Kilian
    Jan 4, 2019 at 11:35
  • 1
    @Kilian because varargs are a compatibility feature with C source and haven't been adapted much. For example, on MSVC they will perform the equivalent of a std::memcpy, without calling constructors or destructors.
    – Quentin
    Jan 4, 2019 at 12:24
3

If the Visitor can always apply, then the code can be as simple as

return std::visit([&](auto e) { return Visitor::apply(s, e); }, e);

But since Visitor cannot always apply, we need to use SFINAE, which requires a set of overloaded function templates. The function templates can be defined like this:

template<class EventType>
static auto applyHelper(State s, EventType e, int)
    -> decltype(Visitor::apply(s, e)) // only enabled if Visitor::apply(s, e) is a valid expression
{
    return Visitor::apply(s, e);
}

template<class EventType>
static State applyHelper(State s, EventType e, long) // long gives a lower precedence
                                                     // in overload resolution when argument is 0
{
    return s;
}

Then the implementation of Applicator::apply can be

  static State apply(State s, Event e) {
      return std::visit([&](auto e) { return applyHelper(s, e, 0); }, e);
  }
3

Well, std::is_invocable_r looks like the tool of choice.
Unfortunately, you would have to get the type of the right overload, which would completely defeat the purpose.

Instead, go one step back and use std::is_detected from library fundamentals TS v2 or equivalent and a template:

template <class... Xs>
using can_Visitor_apply = decltype(Visitor::apply(std::declval<Xs>()...));

if constexpr(std::is_detected_convertible<State, can_Visitor_apply, State&, Event&>())
    return Visitor::apply(s, e);

The advantage is that you have a compile-time-constant to hang arbitrary decisions on. The disadvantage is not (yet) having a function which you can simply just call and forget about it.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.