다음 예제에서 문자열 리터럴이 'v'
으로 시작하지만 verify
으로 시작할 수없는 경우 main
은 static_assert
입니다.constexpr 함수 내부에서 문자열 리터럴에 조건을 정적으로 선언하는 방법은 무엇입니까?
왜 그런가? 문자열 리터럴의 문자 조건을 verify
에서 static_assert
까지 허용 할 수 있습니까?
#include <cstddef>
template <std::size_t N>
constexpr char get_first(const char (&str)[N])
{
static_assert(N>1, "must be > 1");
return str[0];
}
template <std::size_t N>
constexpr void verify(const char (&str)[N])
{
static_assert(str[0] == 'v', "must start from v");
}
int main()
{
static_assert(get_first("value") == 'v', "first must be 'v'"); // succeeds
verify("value"); // fails to compile
}
컴파일 오류 :
main.cpp: In instantiation of 'constexpr void verify(const char (&)[N]) [with long unsigned int N = 6]':
main.cpp:19:15: required from here
main.cpp:13:9: error: non-constant condition for static assertion
static_assert(str[0] == 'v', "must start from v");
^~~~~~~~~~~~~
main.cpp:13:9: error: 'str' is not a constant expression
당신은 내가 하나 제안, 문자열이 컴파일시 수 매개 변수가 주장 할 수있는 경우
와 랩을 해제하는
처럼 통화가 보인다. – chris