可以迭代 boost 或 std 元组,但我可以按照运行时确定的顺序进行迭代,同时仍保留类型信息吗?
假设我的元组充满了 Foo
类型的对象:
#include <tuple>
using namespace std;
template <typename ...> void bar(); // Definition omitted.
template <typename ... Ts>
struct Foo {
void doit() { bar<Ts...>(); }
int rank;
};
int main(int argc, char *argv[])
{
auto tup = make_tuple(Foo<int,double>(),
Foo<bool,char,float>());
get<0>(tup).rank = 2;
get<1>(tup).rank = 1;
return 0;
}
我希望能够遍历 Foo
类型的列表,调用它们的 doit
方法,但可以按任意顺序(例如,由 的值定义) 等级
成员。
最佳答案
您将需要实现某种类型删除才能实现这一点。类似的东西
template <typename ...> void bar(); // Definition omitted.
struct FooBase {
virtual void doit() = 0;
int rank;
};
template <typename ... Ts>
struct Foo : public FooBase {
void doit() { bar<Ts...>(); }
};
int main(int argc, char *argv[])
{
auto tup = make_tuple(Foo<int,double>(),
Foo<bool,char,float>());
get<0>(tup).rank = 2;
get<1>(tup).rank = 1;
std::vector<FooBase*> bases;
// fill bases
// sort
// call
return 0;
}
您还可以应用其他有效的机制,例如,不需要修改 Foo,但它们都归结为相同的原理类型删除。我只是提供了该删除的最简单实现。
关于c++ - 按照运行时定义的顺序遍历 C++ 元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8918596/