1

Let's take this example code:

#include <array>
#include <functional>

std::array<std::function<void()>, 5> array;
static_assert(sizeof(array) == sizeof(std::function<void()>) * 5, "Works!");
static_assert(array.size() == 5, "Fails?");

Compiling this trivial example with GCC 6.3.1 gives a rather surprising error...

$ g++ -std=gnu++11 a.cpp 
a.cpp:6:1: error: non-constant condition for static assertion
 static_assert(array.size() == 5, "Fails?");
 ^~~~~~~~~~~~~
a.cpp:6:25: error: call to non-constexpr function ‘constexpr std::array<_Tp, _Nm>::size_type std::array<_Tp, _Nm>::size() const [with _Tp = std::function<void()>; long unsigned int _Nm = 5ul; std::array<_Tp, _Nm>::size_type = long unsigned int]’
 static_assert(array.size() == 5, "Fails?");
               ~~~~~~~~~~^~
In file included from a.cpp:1:0:
/usr/include/c++/6.3.1/array:171:7: note: ‘constexpr std::array<_Tp, _Nm>::size_type std::array<_Tp, _Nm>::size() const [with _Tp = std::function<void()>; long unsigned int _Nm = 5ul; std::array<_Tp, _Nm>::size_type = long unsigned int]’ is not usable as a constexpr function because:
       size() const noexcept { return _Nm; }
       ^~~~
/usr/include/c++/6.3.1/array:171:7: error: enclosing class of constexpr non-static member function ‘constexpr std::array<_Tp, _Nm>::size_type std::array<_Tp, _Nm>::size() const [with _Tp = std::function<void()>; long unsigned int _Nm = 5ul; std::array<_Tp, _Nm>::size_type = long unsigned int]’ is not a literal type
/usr/include/c++/6.3.1/array:90:12: note: ‘std::array<std::function<void()>, 5ul>’ is not literal because:
     struct array
            ^~~~~
/usr/include/c++/6.3.1/array:90:12: note:   ‘std::array<std::function<void()>, 5ul>’ has a non-trivial destructor

Ideone doesn't seem to like that code either - http://ideone.com/R48OUg

Is this a bug or a feature? I'd suspect a bug, as the first static_assert() works perfectly fine, but you never know...

Freddie Chopin
  • 8,440
  • 2
  • 28
  • 58
  • 1
    Well, array::size() is constexpr, but the compiler says in the first note and following error: not usable because your array variable is not constexpr. – Rene Mar 02 '17 at 16:33
  • should still work I think. certainly works in clang – Richard Hodges Mar 02 '17 at 16:40
  • @Rene I think this a mistake in the standard, size() should a *static* constexpr member function. https://stackoverflow.com/questions/21936507/why-isnt-stdarraysize-static – alfC Jun 08 '19 at 21:55

0 Answers0