简体   繁体   中英

Can I make a table of String + lambdas that have the same signature?

I have this pattern:

Thing * y = FindNearestItem();
if (y && (MenuElement * x = FindMenuElementNamed("Identity")))
  x->SetText(FString("%.1f", y));
else if (x)
  x->Clear();
if (y && (MenuElement * x = FindMenuElementNamed("X1")))
  x->SetLocalData(y);
else if (x)
  x->Clear();

Basically, I want to use a static table: [WARNING: really sloppy conceptual code, not valid, I'm a noob, you've been warned]:

struct Table {
  const char * label;
  ?lambda? lambda;
} MyTable[] = {
  "Identity", [] (const char * label, Thing * y) { MenuElement * x = FindMenuElementNamed(label); (y && x) ? x->SetText(FString("%.1f", y)) : x->Clear(); },
  "X1", [] (const char * label, Thing * y) { MenuElement * x = FindMenuElementNamed(label); (y && x) ? x->SetLocalData(y) : x->Clear(); },
};

Thing * y = FindNearestItem();
for (int i = 0; i != countof(MyTable); ++i)
  MyTable[i].lambda(MyTable[i].label, y);

PLEASE keep in mind that that the action differs for each label - each row in my table.

So the pattern is mostly the same, but the variance is in the action taken, though it uses the same set of data (x,y,label) in each case. But I cannot simply call x->DoAppropriateThingFor(label,y); I'd just be back to creating a long if/else cascade based on label...

Feel free to ask me for further clarification. I'm muddling around in the dark with lambdas since I've not had a chance to really use them yet...

As long as all of the lambdas are captureless (ie, the [] is empty), you can use a function pointer:

struct Table {
    const char* label;
    void (*lambda)(const char*, Thing*);
};

If any of the lambdas are stateful (ie, the [] is not empty), then you can't use a function pointer. You can use std::function , though:

struct Table {
    const char* label;
    std::function<void(const char*, Thing*)> lambda;
};

Visual C++ 2010 does not support the lambda-to-function-pointer conversion (that conversion was added to the language after Visual C++ 2010 was released), but the Visual C++ 11 Developer Preview does support the conversion. If you are using Visual C++ 2010, you can use the std::function solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM