运行时在boost::mpl::vector中查找第一个匹配项
Runtime find first match in boost::mpl::vector
我有一个boost::mpl::vector
,现在需要一个模板(函数),它在类型上"迭代",直到找到第一个匹配(在运行时)。类似于boost::fusion::find_if
的东西,但没有序列作为运行时值。
会把它想象成这样工作吗:
typedef boost::mpl::vector<Foo, Bar> Types;
template< typename T >
struct Finder {
bool operator()() const;
};
struct Callback {
template< typename T >
void operator()();
};
Callback callback;
magic_find_if<Types, Finder>(callback);
在mpl/fusion(找不到)中,这样的事情已经可能了吗
我知道,Callback::operator()
的所有变体都会被"实例化",但这没关系。可以想象用Variadic Templates实现这一点,但遗憾的是,我一直使用C++98。
我建议将过滤器和回调组合成一个条件操作:
template <template<typename> class Finder, typename Callback>
struct ConditionOperation {
ConditionOperation(Callback cb = {}) : _callback(std::move(cb))
{ }
template <typename T>
void operator()(boost::type<T>) const {
if (Finder<T>()())
_callback.template operator()<T>();
}
private:
Callback _callback;
};
然后,在Eric Niebler的回答后,你可以自由地写下:
ConditionOperation<Finder, Callback> op;
mpl::for_each<Types, boost::type<mpl::_1> >(op);
这是一个完整的演示
在Coliru上直播
#include <boost/type.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>
#include <iostream>
struct Foo { enum { id = 879 }; };
struct Bar { enum { id = 321 }; };
struct Qux { enum { id = 555 }; };
typedef boost::mpl::vector<Foo, Bar, Qux> Types;
template <typename T>
struct Finder {
bool operator()() const { return T::id > 500; }
};
struct Callback {
template<typename T> void operator()() const {
std::cout << __PRETTY_FUNCTION__ << "n";
}
};
template <template<typename> class Finder, typename Callback>
struct ConditionOperation {
ConditionOperation(Callback cb = {}) : _callback(std::move(cb))
{ }
template <typename T>
void operator()(boost::type<T>) const {
if (Finder<T>()())
_callback.template operator()<T>();
}
private:
Callback _callback;
};
int main() {
using namespace boost;
ConditionOperation<Finder, Callback> op;
mpl::for_each<Types, boost::type<mpl::_1> >(op);
}
打印
void Callback::operator()() const [with T = Foo]
void Callback::operator()() const [with T = Qux]
cco boost::mpl::for_each而不实例化
相关文章:
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 代码以查找数组中的最大数字,但它仅将第一个数字显示为最大数字. 有人请告诉我为什么
- 如何在数组的一部分中查找特定值的第一个元素
- 查找数组的第一个和最后一个索引,其中 from 和 to 元素的顺序总和最大
- 从文件的一行中查找数字的平均值,避免使用第一个单词
- C++ 查找未排序数组中第一个缺失的正值
- 在向量C++中查找特定的第一个和最后一个索引<float>
- 如何使用 std::find 从向量的第一个元素中查找字符串<字符串对<字符串、字符串> >类型?
- 查找第一个文件W通配符匹配
- 查找第一个文件/查找下一个文件不返回文件夹中的所有文件
- C++ - 查找数组中第一个和最后一个负数之间的数字
- 查找一个区域中未包含在另一个区域中的第一个元素
- 查找第一个文件问题无法使任何示例正常工作。
- 提取所有文件名 - 查找第一个文件
- 查找第一个文件在根路径上失败
- C++在具有O(n)空间的数组中查找第一个非重复整数
- Win32 查找第一个文件非终止通配符扩展
- 运行时在boost::mpl::vector中查找第一个匹配项
- C++从映射中的第一个查找对
- 字符串查找第一个非的 C++ 问题