且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基本和复杂类型的通用for循环

更新时间:2022-10-14 22:57:11

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

  ;类型名称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.