I learnt from here that args is not a constant expression. Now my question is: What should I modify in the given program so that I will be able to have an static_assert in the first variant without getting a compile time error.
In the following code:
#include <array>
template<typename... Args>
auto constexpr CreateArrConst(Args&&... args)
{
std::array arr
{
args...
};
//i want to have an static_assert here without error
return arr;
}
template<typename... Args>
auto constexpr CreateArrConst_NotWorking(Args&&... args)
{
constexpr std::array arr
{
args...
};
static_assert(arr.back() == 4);
return arr;
}
int main()
{
static_assert(CreateArrConst(4).back() == 4);
// uncomment this to reproduce compile error
// static_assert(CreateArrConst_NotWorking(4).back() == 4);
return 0;
}
Here's a link to reproduce: https://godbolt.org/z/zjrP1Kvn7
argsare not compile-time constants. So when the function is compiled, there is no way for the compiler to check the static assertion. You could be calling the function with any arguments. If you need this, make the function parameters template parameters instead.static_assert(arr.back() == 4);inside theCreateArrConstthen it won't work either. Demo. The reason is the same as explained in here and also by user17732522. I think you should phrase this follow up question a little differently so that it won't be the same as the original here.