0

integer_sequence を使用して、数値の範囲がすべて特定の値を下回っているかどうかを判断したいと考えています: is_range() は true を返し、そうでない場合は false を返します。以下のように:

#include<utility> 
#include<iostream> 
using namespace std; 
template <std::size_t N, std::size_t... Ix> 
bool in_range(std::index_sequence<Ix...>) { 
   return ((Ix < N) && ...); 
} 
int main() 
{ 
     cout<<in_range<10>({1,2,30})<<endl; 
     cout<<in_range<10>(1,2,3)<<endl; 
     return 0; 
} 

clang3.8 を使用してコンパイルしましたが、失敗しました。

$ clang++ m.cpp -std=c++1z 
m.cpp:5:37: error: template argument for template type parameter must be a type 
bool in_range(std::integer_sequence<Ix...>) { 
                                     ^~~~~ 
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.3.1/../../../../include/c++/5.3.1/utility:229:21: note: 
       template parameter is declared here 
   template<typename _Tp, _Tp... _Idx> 
                     ^ 
m.cpp:10:11: error: no matching function for call to 'in_range' 
     cout<<in_range<10>({1,2,30})<<endl; 
           ^~~~~~~~~~~~ 
m.cpp:11:11: error: no matching function for call to 'in_range' 
     cout<<in_range<10>(1,2,3)<<endl; 
           ^~~~~~~~~~~~ 
3 errors generated.

コードを修正するにはどうすればよいですか? フォールド表現の私の理解が間違っていると思います

それを修正する方法は?

4

1 に答える 1

3

ここでは必要ありませんindex_sequence。比較する数値のリストをテンプレート引数として渡すだけです。

template <std::size_t N, std::size_t... Ix> 
bool in_range() { 
   return ((Ix < N) && ...); 
}
cout<<in_range<10,1,2,30>()<<endl;

または、それらを引数として関数テンプレートに渡したい場合

template <std::size_t N, typename... Ix> 
bool in_range(Ix... ix) { 
   return ((ix < N) && ...); 
}
cout<<in_range<10>(1U,2U,30U)<<endl; 

最後に、ブレース初期化リストを渡せるようにしたい場合in_rangeは、initializer_list<size_t>. それ以外の場合、ブレース初期化リストは式ではないため、テンプレートの引数の推論は失敗し、型がありません。

template <std::size_t N> 
constexpr bool in_range(std::initializer_list<std::size_t> ix) { 
    for(auto i : ix) {
        if(i >= N) return false;
    }
    return true;
}
cout<<in_range<10>({1,2,30})<<endl; 

ライブデモ

于 2016-07-13T04:58:32.897 に答える