mercredi 21 janvier 2015

C++: Why is this constexpr not a compile time constant

In the following C++11 code, the last call to arraySize causes a compile error. Apparently this is because y is a runtime sized array, and the arraySize template parameter N cannot be deduced for y. I don't understand why x is a compile time sized array, but y ends up runtime sized. The arraySize template function is taken directly from Scott Meyers' "Effective Modern C++" Item 1.



#include <cstddef>

template<typename T, std::size_t N>
constexpr std::size_t arraySize(T(&)[N]) noexcept { return N; }

struct S
{
char c[10];
};

int main()
{
S s;
S* ps = &s;

char x[arraySize(s.c)];
char y[arraySize(ps->c)]; // why is y a runtime sized array?

arraySize(x);
arraySize(y); // error !?

return 0;
}

Aucun commentaire:

Enregistrer un commentaire