How to get std::array's size at compile time
Solved
C++ Gurus
-
Hello,
I have a function which returns a std::array and I want to have some logic based on the size of the array at compile time. Is there a way to get the size of the array off the return value of my function. Code looks something like this:auto someFunction() { return std::array<double, 14>{ 0.1, ..., ...}; }
And I want to plug it into a
if constexpr
to branch out a specific case. Something akin to this:constexpr decltype(someFunction().size()) size = ...; if constexpr (size > 10) { // Do special stuff }
Is this possible at all?
-
I's very easy, you just use
std::tuple_size
. The naming is misleading but it does its job#include <iostream> #include <array> #include <type_traits> auto someFunction(){ return std::array<double,3>{1.1,2.2,3.3}; } int main() { if constexpr (std::tuple_size<std::result_of<decltype(someFunction)&()>::type>::value > 1) std::cout<<"More than 1"; return 0; }
-
Hi
Or like this which also seems to work#include <array> void Nurse(); void Nuke(); constexpr auto someFunction() { return std::array<double, 14>{ 0.1}; } void test() { constexpr decltype( someFunction().size() ) size = someFunction().size(); if constexpr (size > 10) { Nuke(); } else { Nurse(); } }
see here
https://godbolt.org/z/Ktt36GBut @VRonin version seems nicer :) \o/
-
Thanks for the input guys, much appreciated!