我一直试图想办法让我的类方法接受任意数量的回调函数,运行所有这些函数,然后存储输出。我认为这是有效的,但有没有办法我可以做到这一点,我不必让用户将所有回调函数包装到一个向量中?这也只是感觉凌乱。随意提及其他不理想的事情。
#include <iostream>
#include <functional>
#include <vector>
class MyObj{
public:
// where I store stuff
std::vector<double> myResults;
// function that is called intermittently
void runFuncs(const std::vector<std::function<double()> >& fs){
if ( myResults.size() == 0){
for( auto& f : fs){
myResults.push_back(f());
}
}else{
int i (0);
for( auto& f : fs){
myResults[i] = f();
i++;
}
}
}
};
int main(int argc, char **argv)
{
auto lambda1 = [](){ return 1.0;};
auto lambda2 = [](){ return 2.0;};
MyObj myThing;
std::vector<std::function<double()> > funcs;
funcs.push_back(lambda1);
funcs.push_back(lambda2);
myThing.runFuncs(funcs);
std::cout << myThing.myResults[0] << "\n";
std::cout << myThing.myResults[1] << "\n";
std::vector<std::function<double()> > funcs2;
funcs2.push_back(lambda2);
funcs2.push_back(lambda1);
myThing.runFuncs(funcs2);
std::cout << myThing.myResults[0] << "\n";
std::cout << myThing.myResults[1] << "\n";
return 0;
}
答案 0 :(得分:1)
这样的事情,也许是:
t:flip `date`sym`close`last_date`last_close!(`t1`t1`t2`t2`t3`t3`t4`t4`t5`t5`t1`t1;`A`B`A`B`A`B`A`B`A`B`A`B; 5 10 6 11 5 11 4 12 5 11 6 13; ```t1`t1`t2`t2`t3`t3`t4`t4`t5`t5; 0n 0n 5 10 6 11 5 11 4 12 5 11)
date sym close last_date last_close
t1 A 5
t1 B 10
t2 A 6 t1 5.0
t2 B 11 t1 10.0
t3 A 5 t2 6.0
t3 B 11 t2 11.0
t4 A 4 t3 5.0
t4 B 12 t3 11.0
t5 A 5 t4 4.0
t5 B 11 t4 12.0
t1 A 6 t5 5.0
t1 B 13 t5 11.0
然后你可以把它称为
template <typename... Fs>
void runFuncs(Fs... fs) {
myResults = std::vector<double>({fs()...});
}