Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ static compilation of function with a variable number or arguments

Tags:

c++

templates

I found myself writing code like this:

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 of doing that, without using vectors or variadic arguments, as speed is important in this context.

like image 871
JavaNewbie Avatar asked Jan 09 '23 05:01

JavaNewbie


1 Answers

You could try this:

#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 there is a proposal for C++17 to include custom expansion of variadic templates with operators that could avoid this kind of recursion and this ugly (IMO) termination with return true for one argument.

Note: this could possibly not be inlined for many arguments.

like image 64
tsuki Avatar answered Jan 30 '23 11:01

tsuki