I'm pretty new to C++ template programming. I'd like to design a function element
such as e.g.
element<3, 3, 3, 3, 3>
will return 3element<3, 3, 2>
will fail an assertion#include <iostream> #include <cstdlib> namespace meta { template<typename T> constexpr T element(T x) { return x; } template<typename T, typename... Ts> constexpr T element(T x, Ts... xs) { constexpr T oth = element(xs...); // $C$ static_assert(oth == x, "element Mismatch"); return x; } template<int... DIMS> void get_elements() { std::cout << "elements " << element(DIMS...); // $A$ } } int main(int argc, char ** argv) { meta::get_elements<2, 3, 4>(); // $B$ static constexpr int D1 = 3, D2 = 3; meta::get_elements<D1, D2>(); }
But GCC with std=c++14
is failing with
In instantiation of ‘constexpr T meta::element(T, Ts ...) [with T = int; Ts = {int, int}]’:
$A$: required from ‘void meta::get_elements() [with int ...DIMS = {2, 3, 4}]’
$B$: required from here
$C$: error: ‘xs#0’ is not a constant expression
$C$: error: ‘xs#1’ is not a constant expression
I'd like to exploit recursion to perform an equality check on each template argument in the list, and return one of them if they're all equal.