yuniktmr
yuniktmr

Reputation: 83

Passing lambda function as parameter C++

I'm working on passing lambda functions R1 and R2 to my template function F. But, I'm not sure if I'm doing this correctly.

The Function F is supposed to use all the parameters from the main function and perform the related calculations (Newton's method of root approx.).

I'm new to working with template functions. So, any help would be much appreciated.

//main.cpp
    #include <iostream>
    #include "Funct.h"
    using namespace std;

    int main()
    {

        auto f1 = [](long double x) { return (x * x) - 2; };
        auto f2 = [](long double x) { return (2 * x);
        auto RV1 = F<long double>(1.0L,1.0E-20L,f1(1.0L),f2(1.0L));
        return 0;


    }

    //Funct.h
    #include <iostream>
    #include<cmath>
    template<typename T> T F(long double guess, long double tolerance,T ((*f)(const T x)), T((*df)(const T x)));
    template<typename T> T F(long double guess, long double tolerance,T ((*f)(const T x)), T((*df)(const T x)))
    {

    }

Upvotes: 8

Views: 25024

Answers (3)

Abet
Abet

Reputation: 123

This old-school style might still be of help like for example in an async opration.

void AsyncOperator(bool(*callback)(void*, void*), void* param)
{
   while(true)
   {
      if (specific_condition_is_met)
      {
         if (callback(any_result, param)==false)
            return;
      }
      else if (callback(any_result_again, param))
         break;
   }
}

Upvotes: 2

Jarod42
Jarod42

Reputation: 218238

You might use:

template <typename F1, typename F2>
long double F(long double guess,
              long double tolerance,
              F1 f,
              F2 der)
{
    f(4.2); // call function
    der(4.2);
    // ...
}

With usage similar to:

auto f = [](long double x) { return (x * x) - 2; };
auto derived = [](long double x) { return 2 * x; };
auto RV1 = F(1.0L, 1.0E-20L, f, derived);

Upvotes: 7

Petok Lorand
Petok Lorand

Reputation: 973

First, as mentioned by @tkausl, you should not call the lambdas when you pass them as parameters, because this way the are automatically evaluated and produce values(long doubles in this case), but your function expects a function as a parameter.

Instead you should call the functions you give as parameters in the called function itself(F in this case).

You can use std::function to describe a function prototype, thus avoiding the "ugly" function pointers.

First you need to include the <functional> header file from the standard library.

Then you can write something like this:

template <typename T>
using Func = std::function<T(T)>;

template <typename T>
T F(long double guess, long double tolerance, Func<T> f, Func<T> df); 

Where in std::function<long double(long double)> the type in the parentheses denote the type of the function arguments and the type before the parentheses is the return type of the function prototype;

Upvotes: 9

Related Questions