C++ 14引入通用lambda(在lambda的簽名中使用auto關鍵字時)。通用(多形)lambda的C++ 17矢量
有沒有辦法將它們存儲在一個向量與C + + 17?
我知道這個存在的問題,但它不適合我的需求:Can I have a std::vector of template function pointers?
這是說明我希望做一個什麼樣的代碼。 (請參閱底部的筆記纔回答)
#include <functional>
#include <vector>
struct A {
void doSomething() {
printf("A::doSomething()\n");
}
void doSomethingElse() {
printf("A::doSomethingElse()\n");
}
};
struct B {
void doSomething() {
printf("B::doSomething()\n");
}
void doSomethingElse() {
printf("B::doSomethingElse()\n");
}
};
struct TestRunner {
static void run(auto &actions) {
A a;
for (auto &action : actions) action(a);
B b;
for (auto &action : actions) action(b); // I would like to do it
// C c; ...
}
};
void testCase1() {
std::vector<std::function<void(A&)>> actions; // Here should be something generic instead of A
actions.emplace_back([](auto &x) {
x.doSomething();
});
actions.emplace_back([](auto &x) {
x.doSomethingElse();
});
// actions.emplace_back(...) ...
TestRunner::run(actions);
}
void testCase2() {
std::vector<std::function<void(A&)>> actions; // Here should be something generic instead of A
actions.emplace_back([](auto &x) {
x.doSomething();
x.doSomethingElse();
});
actions.emplace_back([](auto &x) {
x.doSomethingElse();
x.doSomething();
});
// actions.emplace_back(...) ...
TestRunner::run(actions);
}
// ... more test cases : possibly thousands of them
// => we cannot ennumerate them all (in order to use a variant type for the actions signatures for example)
int main() {
testCase1();
testCase2();
return 0;
}
注:
- 的
A
,B
和TestRunner
的代碼不能改變,測試用例只有代碼 - 我不我不想討論像這樣編碼測試是好還是不好,這是無關緊要的(這裏使用的測試術語只是爲了說明我不能枚舉所有的lambda表達式(爲了使用它們的變體類型.. ))
auto是C++ 14中TestRunner的有效函數參數(https://ideone.com/4931Ht) – infiniteLoop
多形態解決方案非常聰明+1。 –
@infiniteLoop使用'auto'在[wandbox]上查看它(http://melpon.org/wandbox/permlink/qrrFmVRri4bxM0cy)。請注意,這是一個GCC擴展,而不是C++ 14中用於免費函數的有效參數。 – skypjack