通过多种类型循环

Ria*_*iaD 3 c++ loops

假设我想用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

Evg*_*yuk 6

Boost.MPL

可以通过类型列表来实现- 它们在现代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 Variadic模板

另一种选择是使用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)