std :: array< ...>的大小不是constexpr?

时间:2017-03-02 16:27:23

标签: c++ c++11 constexpr

我们来看看这个示例代码:

#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?");

用GCC 6.3.1编译这个简单的例子给出了一个相当令人惊讶的错误......

$ 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似乎不喜欢该代码 - http://ideone.com/R48OUg

这是一个错误还是一个功能?我怀疑是一个错误,因为第一个static_assert()完全正常,但你永远不会知道......

0 个答案:

没有答案