Tell me how in c ++ 11 you can implement the following functionality:

1) I have a data filtering function

typedef bool(*filteredFunc)(const CPacketData&);

which I will use to process the input

2) there is a structure containing data processing parameters (input conditions, output data)

 struct CStatisticsData { // служебная информация filteredFunc m_filteredFunc; // статистика CStatistics m_output; CStatisticsData(const filteredFunc filteredFunc); }; 

3) data is processed in different ways, therefore, the input parameters and output data are different, but everything is stored in the same vector

 typedef std::vector<CStatisticsData> data_t; 

which I pre-fill as follows:

 data_t allData; allData.push(CStatisticsData(myFunc1)); allData.push(CStatisticsData(myFunc2)); allData.push(CStatisticsData(myFunc3)); 

and the functions themselves myFunc1 , myFunc2 , myFunc3 describe above

Question:

since the functions are small, I would like for clarity to place them immediately in initialization, as in JS:

 data_t allData; allData.push(CStatisticsData(function(params){ return (params.name == 'x'); })); 

Tell me how to do it right? As I understand it, in essence, lambda functions, but they are probably differently set and used than ordinary functions as parameters?

    2 answers 2

     typedef std::function<bool(const CPacketData&)> filteredFunc; ... data_t allData; // Простая лямбда allData.push(CStatisticsData([](const CPacketData& params){ return (params.name == 'x'); })); //Лямбда с внешними параметрами bool externalFlag = readFromSomewhere(); allData.push(CStatisticsData([externalFlag](const CPacketData& params){ return externalFlag ? (params.name == 'x') : false; })); // Обычные функции allData.push(CStatisticsData(myFunc3)); allData.push(CStatisticsData(myFunc3)); allData.push(CStatisticsData(myFunc3)); 
    • ffk, and instead of lambda expression, can I substitute the usual function? - Zhihar
    • @Zhihar, yes you can - ffk

    If your handler functions do not capture external variables (empty capture), then you are all set and nothing needs to be done or changed. Your

     typedef bool(*filteredFunc)(const CPacketData&); 

    already perfectly compatible with lambdas with an empty capture. Those. write immediately

     data_t allData; allData.push([](const CPacketData &params) { return params.name == 'x'; }); 

    Another thing, if you suddenly need a lambda with capture. But in fact, you do not need them. Your CPacketData , in theory, should serve as a “capture” implemented manually. But if you still need capture, then the easiest way is to go to std::function<> .