dmlc / treelite

Universal model exchange and serialization format for decision tree forests
https://treelite.readthedocs.io/en/latest/
Apache License 2.0
730 stars 98 forks source link

Use std::variant to implement type-based dispatching #472

Closed hcho3 closed 1 year ago

hcho3 commented 1 year ago

Currently, we use class inheritance to implement type-based dispatching . The approach often leads to tons of boilerplate, due to the repetition of the following dispatching logic:

void Dispatch(Func func, GenericPtr ptr, TypeInfo underlying_type /* ... */) {
  if (underlying_type == TypeInfo::type_a) {
    func(dynamic_cast<A>(ptr) /* ... */);
  } else if (underlying_type == TypeInfo::type_b) {
    func(dynamic_cast<B>(ptr) /* ... */);
  }  /* ... */
}

The boilerplate is worse for Model::Dispatch, where dispatching happens with two type variables.

Solution: Use std::variant<> instead. It will reduce boilerplate and result into more idiomatic C++.