c++ - boost 元组部分迭代?

标签 c++ boost metaprogramming tuples template-meta-programming

我正在尝试使用 boost 元组来避免一些虚函数开销,但我无法让它正常工作。我有一个尝试处理输入的“处理程序” vector ,一旦其中一个返回 true,我就不想调用其余的。

C++11 不可用。

首先,当前的虚拟实现如下所示:

std::vector<Handler*> handlers;

//initialization code...
handlers.push_back(new Handler1);
handlers.push_back(new Handler2);
handlers.push_back(new Handler3);

//runtime code
for(std::vector<Handler*>::iterator iter = handlers.begin();
    iter != handlers.end() && !(*iter)->handle(x); ++iter) {}

因为我在编译时拥有所有类型,所以我希望能够将其表示为一个元组,如下所示:

boost::tuple<Handler1,Handler2,Handler3> handlers;

//runtime code
???
// should compile to something equivalent to:
// if(!handlers.get<0>().handle(x))
//   if(!handlers.get<1>().handle(x))
//     handlers.get<2>().handle(x);

理想情况下,不会有虚函数调用,任何空函数体都会内联输出。使用 boost::fusion for_each 似乎这几乎是可能的,但我需要短路行为,一旦其中一个处理程序返回 true,其余的就不会被调用。

最佳答案

你可以尝试这样的事情:

void my_eval() {}
template<typename T, typename... Ts>
void my_eval(T& t, Ts&... ts) {
  if(!t.handle(/* x */))
    my_eval(ts...); 
}

template<int... Indices>
struct indices {
  using next_increment = indices<Indices..., sizeof...(Indices)>;
};

template<int N>
struct build_indices {
  using type = typename build_indices<N - 1>::type::next_increment;
};
template<>
struct build_indices<0> {
  using type = indices<>;
};

template<typename Tuple, int... Indices>
void my_call(Tuple& tuple, indices<Indices...>) {
    my_eval(std::get<Indices>(tuple)...);
}
template<typename Tuple>
void my_call(Tuple& tuple) {
    my_call(tuple, typename build_indices<std::tuple_size<Tuple>::value>::type());
}

要使用,只需将您的元组传递给 my_call

关于c++ - boost 元组部分迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14150861/

相关文章:

python - 在阻塞的 boost c++ 方法中,如何在 Python 中捕获中断信号?

c# - .NET 类属性条件

c++ - 通过模板参数初始化静态 vector

c++ - 堆分配变量的结构成员对齐

c++ - 如何使用 C++ 输出可执行文件

c++ - 如何在 cmd c++ boost::asio 中通过网络在两台或多台计算机之间传输一个字符串?

javascript - 如何在 JavaScript 中模拟宏?

C++:部分模板特化

c++ - 具有特殊字符的 QFileDialog 问题

c++ - boost socket 。格式化/重新安装 ubuntu 后,工作代码不再工作。权限问题?