1
Expensive,
I’m trying to do some things in C++, but I’m still starting both in language and in the functional paradigm. What I need is to insert a function lambda
in a pair
. The first member of pair
will be an object struct
, and the second, the lambda function. My lambda function receives as parameters a struct
and a vector<string>
and returns a string
, something like:
auto lambda = [](struct &s, vector<string> &v){
return (s.atributo + " " + v[0]);
};
In that case, the pair
would be something like:
pair<struct, funcao_lambda> par;
I have encountered many type errors (when trying to insert the lambda function in a map
), and in the search for a solution, I found something I can solve: a generic class that wraps the Lambda functions and has a lambda function execution method. I found an example of a generic class for this, but due to my lack of knowledge of the language, I don’t know how to change it to accept functions with parameters (no capture):
class T {
private:
double (*expression)();
public:
T(double (*exp)()) : expression(exp) {}
double execute() {
return this->expression();
}
};
int main() {
T t([]()->double {return 1+1;});
double val = t.execute(); // val = 2
return 0;
}
In addition to changing the types double
for string
, What else do I need to change in the class to get lambda functions with parameters (no capture, only parameters)? The idea is that T-types are created in this form:
T t([](struct &s, vector<string> &v) -> string {
return (s.atributo + " " + v[0]);
});
And be executed in that form:
string texto = t.execute(struct, vector<string>);
Is that possible? And more importantly, it will be possible to insert this type T into the pair
?
I appreciate any help.
First of all, thank you so much for your help! Very precise! Of course I need to study C++ a lot... In your example, one of the attributes of the lambda function is the first member of the pair, and that’s exactly what I need. I believe this solution will solve my problem. And I will use the map again, because in it I will reference which struct pair and lambda function I should use later. But I still have some doubts, which I will put in the next comment because of space :)
– Daniel Elias
– Daniel Elias
Answering your questions: 1) Yes, if you need a string key, switch to string; 2) There are different methods for inserting into a string
map
, I usedinsert()
, passing apair
as parameter, but this is something you need to study; 3) the function returns astring
, then, yes, you can store the return value in a variable of typestring
.– user142154
@Danielelias, mark the answer as "accept", she’s very good
– zentrunix
Yes, it’s excellent! I forgot it, I’m already dialing. I’m solving some other problems here.
– Daniel Elias