加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 循环使用多种类型

发布时间:2020-12-16 09:43:59 所属栏目:百科 来源:网络整理
导读:假设我想用vector int,vector bool,vector string进行测试.我想写这样的东西: for(type T in {int,bool,string}){ vectorT v; for(int i = 0; i 3; ++i){ v.push_back(randomValueT()); } assert(v.size() == 3);} 我知道语言中没有这样的功能,但有可能以某
假设我想用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);
}

我知道语言中没有这样的功能,但有可能以某种方式模仿吗?在某些库中是否存在此功能,例如boost?

解决方法

Boost.MPL

有可能通过类型列表完成 – 他们将在Modern C++ Design: Generic Programming and Design Patterns Applied由Andrei Alexandrescu详细讨论

检查Boost.MPL库.例如 – boost::mpl::for_each

LIVE DEMO

#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,string>>(Benchmark());
}

输出是:

Testing int
Testing bool
Testing std::string

C 11 Variadic模板

另一种选择是使用C 11可变参数模板:

LIVE DEMO

#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,string>(Benchmark());
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读