Need a variadic template function that accepts a arbitrary number of ints!

Why is this not working?

1
2
template<int...Counts>
static bool allNonZero(Counts...counts);


Regards,
Juan
Why is this not working?

Counts is a pack of non-type template parameters. Very roughly, think of Counts... as a comma-separated list of integer literals, as in
1, 2, 3, 4, 5
not
int, int, int, int, int.

Instead, try
1
2
3
4
static bool allNonZero(std::initializer_list<int> xs)
{ 
  std::find(xs.begin(), xs.end(), [](int x) { return xs != 0; }) != xs.end(); 
}


Or,
1
2
3
4
5
6
template<Ts... Counts>
static bool allNonZero(Counts...counts)
{
  static_assert((std::is_same_v<Counts, int> && ...));
  return (counts && ...);
}


Otherwise put (std::is_same_v<Counts, int> && ...) within a static_assert or within enable_if.

If you have access to C++20, prefer a requires clause in place of enable_if or whatever
1
2
bool allNonZero(auto... xs) requires (std::same_as<decltype(xs), int> && ...) 
{ return (xs && ...); };

Last edited on
mbozzi I think you meant:

1
2
3
4
bool allNonZero( std::initializer_list<int> xs)
{
	return std::find_if(xs.begin(), xs.end(), [](int x) {return x == 0; }) == xs.end();
}


This works!
So my conclusion is: 1- use find_if
2- use x and not xs inside lambda
3- test x == 0 inside lambda
4- ensure x == 0 is not found (compare return to xs.end())


Thanks!!

Juan
I think you meant

Botched that one quite badly, didn't I?

Glad it helped anyway.
Last edited on
I did thanks!!!
Registered users can post here. Sign in or register to post.