2

I am using Visual-C++ 2013 (But this tag seems to be not available here).

I have a struct

struct init_param{
    bool (*validation)(double**);
};

And I want to cast a member function ValidateParameters of the instance model. So I tried to use a Lambda Expression:

init_params params;
params.validation = [&model](double **par){return model.ValidateParameters(par); };

But the Compiler says:

error C2440: '=': 'main::< lambda_d8b99bf9b28e45558a48b7e9148b3202>' can not be converted into 'bool (__cdecl *)(double **)'

How to proceed? Or what is the easiest way to change the init_param struct, that hte Lambda expression would work?

0

2 Answers 2

2

You can probably just change validation to a std::function object:

#include <functional>

struct init_param
{
    std::function<bool(double**)> validation;
};
Sign up to request clarification or add additional context in comments.

Comments

1

A lambda with a capture cannot be converted to a function pointer. Your lambda captures model.

C++ standard section § 5.1.2 [expr.prim.lambda] :

The closure type for a non-generic lambda-expression with no lambda-capture has a public non-virtual non- explicit const conversion function to pointer to function with C ++ language linkage

You can use std::function<> instead :

using namespace std::placeholders;

struct init_params{
    std::function<bool(double**)> validation;
};

struct modelType
{
    bool ValidateParameters(double** par) { return false; }
};


int main () {
    init_params params;
    modelType model;
    params.validation = std::bind(&modelType::ValidateParameters, &model, _1);
}

4 Comments

What are the advanteges in using std::bind instead of a ordinary Lambda Expression? And why do you not use std::bind1st?
@quantdev You can use a lambda. You can't use a function pointer.
std::bind is c++11 and makes std::bind1st and the like almost useless. There's no real advantage here, it just is that you cant use function pointer since your lambda captures model
@T.C. comment reworded , thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.