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?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Matthias
  • 908
  • 1
  • 7
  • 22

2 Answers2

2

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

#include <functional>

struct init_param
{
    std::function<bool(double**)> validation;
};
user673679
  • 1,327
  • 1
  • 16
  • 35
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);
}
quantdev
  • 23,517
  • 5
  • 55
  • 88
  • What are the advanteges in using `std::bind` instead of a ordinary Lambda Expression? And why do you not use `std::bind1st`? – Matthias Feb 01 '15 at 13:38
  • @quantdev You can use a lambda. You can't use a function pointer. – T.C. Feb 01 '15 at 15:24
  • 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 – quantdev Feb 01 '15 at 15:26
  • @T.C. comment reworded , thanks – quantdev Feb 01 '15 at 15:27