std :: span의 모든 생성자는 constexpr로 선언되었지만 constexpr 컨텍스트에서 작동하도록 할 수는 없습니다. 아래의 constexpr을 주석 해제하면 컴파일 오류가 발생합니다.
#include <array>
#include <span>
int main()
{
constexpr int carray[3] = { 0, 1, 2 };
constexpr std::array<int, 3> array{ 0, 1, 2 };
using S = std::span<const int, 3>;
/*constexpr*/ S span1{ array.data(), 3 };
/*constexpr*/ S span2{array.begin(), array.end()};
/*constexpr*/ S span3{carray};
/*constexpr*/ S span4{array};
}
constexpr span 유형을 생성하는 것이 실제로 가능합니까? 생성자가 포인터 또는 참조를 초기화해야 할 때 컴파일 타임에 평가할 수없는 것처럼 보이기 때문에?
답변
정적이 아닌 함수 로컬 변수는 상수 표현식에 사용할 수 없습니다. 주소 안정성이 필요하며 이는 정적 객체에 의해서만 달성됩니다. 코드를 수정
constexpr std::array<int, 3> array{ 0, 1, 2 };
constexpr int carray[3] = { 0, 1, 2 };
int main()
{
using S = std::span<const int, 3>;
constexpr S span1{ array.data(), 3 };
constexpr S span2{array.begin(), array.end()};
constexpr S span3{carray};
constexpr S span4{array};
}
또는
int main()
{
static constexpr std::array<int, 3> array{ 0, 1, 2 };
static constexpr int carray[3] = { 0, 1, 2 };
using S = std::span<const int, 3>;
constexpr S span1{ array.data(), 3 };
constexpr S span2{array.begin(), array.end()};
constexpr S span3{carray};
constexpr S span4{array};
}
을 만들 수 있습니다 constexpr
std::span
.