Boost.MPL
可以使用类型列表来完成——它们在Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu中有详细讨论
检查Boost.MPL库。例如 - boost::mpl::for_each
现场演示
#include <boost/exception/detail/type_info.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/vector.hpp>
#include <iostream>
#include <cassert>
#include <vector>
#include <string>
using namespace boost;
using namespace std;
template<typename T>
T randomValue()
{
return T();
}
struct Benchmark
{
template<typename T>
void operator()(T) const
{
cout << "Testing " << type_name<T>() << endl;
vector<T> v;
for(int i = 0; i < 3; ++i)
{
v.push_back(randomValue<T>());
}
assert(v.size() == 3);
}
};
int main()
{
mpl::for_each<mpl::vector<int, bool, string>>(Benchmark());
}
输出是:
Testing int
Testing bool
Testing std::string
C++11 可变参数模板
另一种选择是使用 C++11 可变参数模板:
现场演示
#include <boost/exception/detail/type_info.hpp>
#include <iostream>
#include <cassert>
#include <vector>
#include <string>
using namespace boost;
using namespace std;
template<typename T>
T randomValue()
{
return T();
}
struct Benchmark
{
template<typename T>
void operator()(T) const
{
cout << "Testing " << type_name<T>() << endl;
vector<T> v;
for(int i = 0; i < 3; ++i)
{
v.push_back(randomValue<T>());
}
assert(v.size() == 3);
}
};
template<typename ...Ts,typename F>
void for_each(F f)
{
auto &&t = {(f(Ts()),0)...};
(void)t;
}
int main()
{
for_each<int, bool, string>(Benchmark());
}