Boost :: any and templates

I am writing a library that includes a large number of pattern tricks and boost :: any. I came across a situation where I have this:

boost::any a1, a2, a3, a4;

... and I need to call a function that looks like this:

template <typename A1, typename A2, typename A3, typename A4>
void somefunc (A1 a1, A2 a2, A3 a3, A4 a4);

I could resort to an indecently nested series of if statements, but assuming I process 10 different types, these are 10,000 if statements! An excellent preventer may help here, but it is still a terrible decision.

Is there a better way to call a boilerplate function with the contents of boost :: any without resorting to such madness? As far as I can tell, no.

+5
source share
1 answer

any , . , . type-erasure, (, boost::any ),

// note that this can easily be adapted to boost::tuple and variadic templates
struct any_container{
  template<class T1, class T3, class T3>
  any_container(T1 const& a1, T2 const& a2, T3 const& a3)
    : _ichi(a1), _ni(a2), _san(a3), _somefunc(&somefunc<T1, T2, T3>) {}

  void call(){ _somefunc(_ichi, _ni, _san); }

private:
  boost::any _ichi, _ni, _san;
  // adjust to your need
  typedef void (*func_type)(boost::any&, boost::any&, boost::any&);
  func_type _somefunc;

  template<class T1, class T2, class T3>
  void somefunc(boost::any& a1, boost::any& a2, boost::any& a3){
    // access any objects with 'boost::any_cast<TN>(aN)'
  }
};
+10

All Articles