Tony Shi
Tony Shi

Reputation: 19

functional conversion with variable number of args to something plain in C++

I need to do something like this:

I have a big black box solver solver(f, ...) that takes a function (for example) as input:

double f(x, a, b, c) {
   return 0.0
}

The a, b, c varies and the solver can detect this.

It is really not very simple to use since if I have 100 parameters I have to write something like:

double f(x, a_0, a_1, ..., a_99) {
    return 0.0;
}

What I want to do is I write a user-friendly variadic function, e.g.

// Variadic function (general form)
template <typename... Args>
double f(double x, Args... args) {
    const double z = (x - std::get<1>(std::make_tuple(args...))) / std::get<2>(std::make_tuple(args...));
    return std::get<0>(std::make_tuple(args...)) * std::exp(-0.5 * z * z);
}

which can be converted to this to pass to solver:

double gaussian(double x, double a, double b, double c) {
    const double z = (x - b) / c;
    return a * std::exp(-0.5 * z * z);
}

How to achieve this in C++?

Upvotes: -1

Views: 100

Answers (1)

Gon&#231;alo Gomes
Gon&#231;alo Gomes

Reputation: 90

Would this solve your problem?

#include <concepts>
#include <cmath>
#include <utility>
#include <tuple>

double funct(std::floating_point auto... ts){
    const auto tuple = std::make_tuple(std::forward<decltype(ts)>(ts)...);
    const double z = (std::get<0>(tuple) - std::get<2>(tuple)) / std::get<3>(tuple);
    return std::get<1>(tuple) * std::exp(-0.5 * z * z);
}

int main()
{
    funct(0.0, 0.0, 0.0, 0.0);
    return 0;
}

or

#include <concepts>
#include <cmath>
#include <utility>
#include <tuple>

template <typename T, typename U>
concept Is = std::same_as<T, U>;

double funct(Is<double> auto... ts){
    const auto tuple = std::make_tuple(std::forward<decltype(ts)>(ts)...);
    const double z = (std::get<0>(tuple) - std::get<2>(tuple)) / std::get<3>(tuple);
    return std::get<1>(tuple) * std::exp(-0.5 * z * z);
}

int main()
{
    funct(0.0, 0.0, 0.0, 0.0);
    return 0;
}

Upvotes: 0

Related Questions