C++ trick to calling an overloaded function by it's number of parameters based on a class template

51 Views Asked by At

I have to build an interface HistoWapper that aggregates a histogram class that has three methods which vary by their parameter count, which I have to call

class Histogram {
  ...
  double Interpolate(double X);
  double Interpolate(double X, double Y);
  double Interpolate(double X, double Y, double Z);
  ...
};

Right now I'm doing a switch on the dimension of my histogram and selecting the correct implementation at runtime.

class HistoWrapper {
  ...
  Histogram hist_;
  int dimension;
  double x_;
  double y_;
  double z_;
  double getValue() {
    if(dimension == 1)
      return hist_.getValue(x_);
    else if(dimension == 2)
      return hist_.getValue(x_, y_);
    else if(dimension == 3)
      return hist_.getValue(x_, y_, z_);
  }
  ...
};

This code has many problems. When the dimension is 1, y_ and z_ are unused variables which take up memory for nothing. And getValue() will be called for millions of values at runtime meaning the branching will be very expensive and inneficient with big data.

The dimension of the histogram is known at compile time.

I'm wondering how I could avoid to do this else if ? Perhaps C++17 constexpr could be used on the dimension with an int using non type template parameters ? Could variadic templates be a solution here too ?

0

There are 0 best solutions below