constexpr 및 static_assert를 가지고 놀고 싶습니다. 사실 constexpr 문자열의 길이를 확인해야하는데 이는 전용 함수에 의해 계산됩니다. 여기에 내가 실행하기 위해 노력하고있어 무엇 : 여기constexpr 및 함수 사용
#include <iostream>
using namespace std;
class Test
{
private :
static constexpr char str[] = "abc";
static int constexpr constStrLength(const char* str)
{
return *str ? 1+constStrLength(str+1) : 0;
}
static constexpr int length = constStrLength(str);
static_assert(length ==3, "error");
public :
static void f()
{
cout << len << endl;
}
};
int main()
{
Test::f();
return 0;
}
을 그리고 오류가 나는 얻을 수있다 :
error: 'static constexpr int Test::constStrLength(const char*)' called in a constant expression static constexpr int len = constStrLength("length ");
을 달성하기 위해 올바른 방법은 무엇입니까?
도움 주셔서 감사합니다.
문자열은 항상'char str [] = "..."'로 초기화되어 있습니까? 왜냐하면이 폼에서 길이를'sizeof (str) -1'로 간단하게 얻을 수 있기 때문이다. – kennytm
@kennytm : 그렇게하면 잘못된 결과가 발생할 수 있습니다. 예를 들어,'sizeof ("abc \ 0def") -1은'constStrLength()'함수가'3'을 산출하는 동안'7'을 생성합니다. –
내 문자열은 항상 이와 같이 정의되어 있지만 실제로 문자열 내부의 \ 0 문자와 관련된 잘못된 동작을 방지해야합니다. 하지만 팁 주셔서 감사합니다;) –