constexpr에서 std :: string을 사용할 수 있습니까?
C ++ 11, Ubuntu 14.04, GCC 기본 툴체인 사용 .
이 코드는 실패합니다 :
constexpr std::string constString = "constString";
오류 : constexpr 변수 'constString'의 'const string {aka const std :: basic_string}'유형이 리터럴이 아닙니다 ... 왜냐하면 'std :: basic_string'에 중요한 소멸자가 없기 때문입니다.
그것은 사용할 수 있습니다 std::string
A의 constexpr
? (분명히 아닙니다 ...) 그렇다면 어떻게? 에서 문자열을 사용하는 다른 방법이 constexpr
있습니까?
아니요, 컴파일러는 이미 포괄적 인 설명을 제공했습니다.
그러나 당신은 이것을 할 수 있습니다 :
constexpr char constString[] = "constString";
런타임시, std::string
필요할 때 를 구성하는 데 사용할 수 있습니다 .
C ++ 17에서는 다음을 사용할 수 있습니다 string_view
.
constexpr std::string_view sv = "hello, world";
A string_view
는 string
객체 시퀀스에 대한 불변의 비 소유 참조 역할을하는 유사 객체입니다 char
.
문제는 사소하지 않은 소멸자이므로 소멸자가에서 제거되면 해당 유형 std::string
의 constexpr
인스턴스 를 정의 할 수 있습니다 . 이렇게
struct constexpr_str {
char const* str;
std::size_t size;
// can only construct from a char[] literal
template <std::size_t N>
constexpr constexpr_str(char const (&s)[N])
: str(s)
, size(N - 1) // not count the trailing nul
{}
};
int main()
{
constexpr constexpr_str s("constString");
// its .size is a constexpr
std::array<int, s.size> a;
return 0;
}
C ++ 20은 constexpr
문자열과 벡터를 추가합니다
다음 제안 이 명백히 받아 들여 졌습니다 : http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0980r0.pdf 그리고 다음과 같은 생성자를 추가합니다 :
// 20.3.2.2, construct/copy/destroy
constexpr
basic_string() noexcept(noexcept(Allocator())) : basic_string(Allocator()) { }
constexpr
explicit basic_string(const Allocator& a) noexcept;
constexpr
basic_string(const basic_string& str);
constexpr
basic_string(basic_string&& str) noexcept;
모든 / 대부분의 메소드의 constexpr 버전 외에도.
GCC 9.1.0부터는 지원되지 않으며 다음은 컴파일되지 않습니다.
#include <string>
int main() {
constexpr std::string s("abc");
}
와:
g++-9 -std=c++2a main.cpp
오류가있는 경우 :
error: the type ‘const string’ {aka ‘const std::__cxx11::basic_string<char>’} of ‘constexpr’ variable ‘s’ is not literal
std::vector
논의 : constexpr std :: vector를 만들 수 없습니다
우분투에서 테스트 19.04.
참고 URL : https://stackoverflow.com/questions/27123306/is-it-possible-to-use-stdstring-in-a-constexpr
'Programing' 카테고리의 다른 글
이 방법으로 숫자의 제곱을 계산할 수 없습니다 (0) | 2020.06.25 |
---|---|
SQL Server 2012 Express 버전의 차이점은 무엇입니까? (0) | 2020.06.25 |
데이터베이스에서 django 객체를 다시로드하십시오. (0) | 2020.06.24 |
지정된 문자열로 시작하는 파일 이름을 가진 모든 파일을 찾으십니까? (0) | 2020.06.24 |
TypeScript에서 숫자를 문자열로 캐스팅 (0) | 2020.06.24 |