I have a performance critical code where I query N indices. How can I check compile-time with a static_assert whether exactly N indices are given, without sacrificing performance?
#include <array>
template<int N>
void test(const std::array<int, N>& indices)
{
// static_assert: has three elements.
return;
}
int main()
{
test<3>({1, 2, 3}); // OK
test<3>({1, 2}); // Needs to crash, because 2 < 3
test<2>({1, 2, 3}); // Crashes, because 3 > 2
test<2>({1, 2}); // OK
return 0;
}
test()so it accepts three arguments of typeint? That means the calling syntax doesn't need the{}for the initialiser (i.e.test(1,2,3)rather thantest({1,2,3})) and a compilation error if you get the number of values wrong. You can also use a variadic template if needed.