使用boost::fusion::for_each实现类型遍历的测试程序
对于一些需要对类型进行遍历操作的场景,使用boost::fusion::for_each可以非常方便地实现。这个函数可以非常优雅地处理模板元编程中的类型列表(例如boost::mpl::vector、std::tuple等),达到遍历列表中每一个类型并执行特定代码块的效果。
下面是一个简单的例子,用于计算一个类型列表中所有类型的大小之和:
#include <iostream>
#include <typeinfo>
#include <boost/fusion/include/for_each.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/accumulate.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/sizeof.hpp>
struct type_size_printer
{
template <typename T>
void operator() (const T&)
{
std::cout << typeid(T).name() << ": " << sizeof(T) << std::endl;
}
};
template <typename T>
struct sum_of_sizes
{
typedef type