Is there anyway I can tell function argument is compile time-constant or not in C++ 11?. I would like to branch the functions body based on the results. For example, like below;
template <T>
size_t get_length(const T &t)
{
return t.size();
}
template <typename T, size_t N>
size_t get_length(const std::array<T, N> &t)
{
return N;
}
// Maybe some template
??? foo(size_t length)
{
...
// If length could be evaluated at compile time,
return std::array<int, length>{};
...
// Otherwise,
return std::vector<int>(length);
}
// ??? and auto should be std::array if bar is std::array, std::vector if bar is std::vector or etc.
auto x = foo(get_length(bar));
I believe this need two task; First it should be able to determine if a value is compile time evaluable or not. Second, convert a value to compile time constant if possible.
Is there anyway one can do this? Or is there any reason this is impossible? It seems some say to use template function, but that forces caller to put compile time constant and not what I am looking for.
constexpr
andstd::enable_if
comes to mind. – Posthorsestd::conditional
but seeking better solution from betters :) – Burinstd::is_constant_evaluated
– Mephiticstd::is_constant_evaluated
returns true if it is called in a constexpr context. They show that on the cppreference in thierconstexpr double power(double b, int x)
example code – Mephiticauto x = foo(42);
, I want the "compile-time value" branch to be taken, butstd::is_constant_evaluated
(andif consteval
) return false here. Being forced to make the variableconstexpr
severely limits the usefulness of what OP wants to do. One needs a compiler extension for this, such as__builtin_constant_p
. – Pasefoo
uniform. – Burinbar
objects, then why not simply skip the step of getting the length at all? You could have separatefoo
overloads accepting arrays or vectors to achieve the same even easier:foo(bar);
. Sure, only covers this specific part, not catches up with any other function returning a size, but it's a starting point at least... – Effervescent