假设我想用vector<int>,测试一些东西vector<bool>,vector<string>.我想写这样的东西:
for(type T in {int, bool, string}){
vector<T> v;
for(int i = 0; i < 3; ++i){
v.push_back(randomValue<T>());
}
assert(v.size() == 3);
}
Run Code Online (Sandbox Code Playgroud)
我知道语言中没有这样的功能,但有可能以某种方式模仿吗?例如,某些库中是否存在此功能boost?
可以通过类型列表来实现- 它们在现代C++设计中详细讨论:由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());
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Testing int
Testing bool
Testing std::string
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用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());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
144 次 |
| 最近记录: |