基本和复杂类型的通用for循环 [英] Generic for loop for elementary and complex type

查看:211
本文介绍了基本和复杂类型的通用for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这两个 std :: vector

  std :: vector< int> v_int(1000); 
std :: vector< T> v_T(1000); //其中T是复制costy类型

如果我需要循环遍历它们需要编辑我可以使用的项目:

  for(const auto item:v_int){
// .. 。
}

for(const auto& item:v_T){//注意&
// ...
}

使用 const auto item:v_T 太糟糕了,因为每次迭代都会执行一次复制。但是,使用 const auto& item:v_int 不是最佳的,但不是那么糟糕。所以如果我需要一个代码来处理他们,我曾经使用 const auto&

:是否有一个通用的方法来编写for循环,将使用最好的声明为他们?例如:

 模板< typename T> 
void iterate(const std :: vector< T> v){
for(const auto / *& * / item:v){// activate&如果T不是基本类型
// ...
}
}


解决方案

您可以使用标准类型特征:

  ;类型名称T> 
using select_type = std :: conditional_t< std :: is_fundamental< T> :: value,
const T,const T&>

template< typename T>
void iterate(const std :: vector< T> v){
for(select_type< T> item:v){// activate&如果T不是基本类型
// ...
}
}


$ b b

然而,我怀疑这样做的智慧。它只是杂乱的代码,这是不可能产生任何区别。


Suppose I have those two std::vector:

std::vector<int> v_int(1000);
std::vector<T> v_T(1000); // Where T is copy-costy type

if I need to loop through them (sepereatly) without the need for editing the items I may use:

for(const auto item:v_int){
    //...
}

for(const auto& item:v_T){ //Note &
    //...
}

Iterating using const auto item:v_T is too bad since a copy will be performed in each iteration. However, using const auto& item:v_int is not optimal but not that bad. So if I need a code that deal with both them I used to use const auto& item:v.

Question: Is there a generic way to write the for loop that will use the best declaration for both of them? Something like:

template <typename T>
void iterate(const std::vector<T> v){
    for(const auto/*&*/ item:v){ // activate & if T is not elementary type
         //...
    }
}

解决方案

You can do this using the standard type traits:

template <typename T>
using select_type = std::conditional_t<std::is_fundamental<T>::value,
                                      const T, const T&>;

template <typename T>
void iterate(const std::vector<T> v){
    for(select_type<T> item:v){ // activate & if T is not elementary type
         //...
    }
}

However, I question the wisdom of doing this. It just clutters the code for something which is unlikely to make any difference.

这篇关于基本和复杂类型的通用for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆