C ++ static compilation with variable number or arguments

I found myself writing code as follows:

template <class T>
inline bool allequal(T a,T b,T c) {return a==b&&a==c;}
template <class T>
inline bool allequal(T a,T b,T c,T d) {return a==b&&a==c&&a==d;}
template <class T>
inline bool allequal(T a,T b,T c,T d,T e) {return a==b&&a==c&&a==d&&a==e;}

I was wondering if there is an automated way to do this, without using vectors or variable arguments, since speed is important in this context.

+4
source share
3 answers

You can try the following:

#include <iostream>

template< typename T >
inline bool allequal( const T& v )
{
  return true;
}

template< typename T, typename U, typename... Ts >
inline bool allequal( const T& v, const U& v1, const Ts&... Vs)
{
  return (v == v1) && allequal( v1, Vs... );
}

int main()
{
    std::cout << std::boolalpha;
    std::cout << allequal(1, 1, 1, 1) << std::endl;
    std::cout << allequal(1, 1, 2, 2) << std::endl;
    return 0;
}

AFAIK offers a proposal for C ++ 17 to include an arbitrary extension of variational patterns with operators that could avoid this kind of recursion and this ugly (IMO) termination with a return truesingle argument.

Note: for many arguments this may not be inlined.

+4
source
#include <algorithm>
#include <iterator>

template <typename T, typename... Args>
bool allequal(T a, Args... rest)
{
    std::initializer_list<T> values = {a, rest...};
    return std::adjacent_find(begin(values), end(values), std::not_equal_to<T>()) == end(values);
}

Working demo

+3
source
template<typename First, typename Second>
bool AllOf(First a, Second b)
{
    return a == b;
}

template<typename First, typename Second, typename... Rest>
bool AllOf(First a, Second b, Rest... r)
{
    return  a == b && AllOf(b, r...);
}


std::cout << AllOf(1, 1,1,1) << "\n";
std::cout << AllOf(1, 1,2) << "\n";
std::cout << AllOf(1,2) << "\n";
std::cout << AllOf(1,1) << "\n";
+2
source

All Articles