How to deduce a native array in a template function?
Feb 16, 2021 at 11:42pm UTC
Hi,
I used to know this but I think I am just exhausted. I want something like this:
1 2 3 4 5 6 7 8 9 10
template <int N, int array[N]>
static bool anyNonZero( int (array&)[N])
{
for ( int i=0; i < N; ++i)
{
if (array[i] != 0)
return true ;
}
return false ;
}
in order to call it like so:
1 2 3 4
int count[2];
if (anyNonZero(count))
{ /////
}
but I get compilation errors!
Please help!
Feb 16, 2021 at 11:55pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14
template < typename T, std::size_t N > using native_array_type = T[N] ;
template < typename T, std::size_t N >
constexpr bool any( const native_array_type<T,N>& arr, const T& value = T{} )
{
for ( const T& v : arr ) if ( v == value ) return true ;
return false ;
}
int main()
{
constexpr const int a[] { 12, 0, 23, 5, 9 } ;
constexpr bool found_zero = any(a) ;
}
Feb 17, 2021 at 6:50am UTC
1 2 3 4 5 6 7 8 9 10
template <int N, typename array> //[EDIT] not type required
static bool anyNonZero( int (&array)[N])
{
for ( int i=0; i < N; ++i)
{
if (array[i] != 0)
return true ;
}
return false ;
}
Last edited on Feb 17, 2021 at 11:12am UTC
Feb 17, 2021 at 10:46am UTC
1 2 3 4 5
template <size_t N>
static bool anyNonZero(const int (&array)[N])
{
return std::any_of(std::begin(array), std::end(array), [](int i) {return i != 0; });
}
Last edited on Feb 17, 2021 at 10:47am UTC
Feb 17, 2021 at 7:54pm UTC
Thanks!!!!
Topic archived. No new replies allowed.