constexpr 和函数的使用
Use of constexpr and functions
我正在尝试使用 constexpr 和 static_assert。我实际上需要检查由专用函数计算的 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 ");
实现它的正确方法是什么?
感谢帮助!
作为constexpr
函数使用的constexpr
函数需要在使用时定义。但是,当你使用 constStrLength()
来 define length
它只是 declared: 成员函数定义在 class 定义实际上只在 class 定义中 声明 !他们的定义在 class 定义之后立即可用,即在右括号之后非正式地说。
解决方法是在使用前定义 constStrLength()
,例如,作为非成员函数或通过在基础 class.
中定义它
我正在尝试使用 constexpr 和 static_assert。我实际上需要检查由专用函数计算的 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 ");
实现它的正确方法是什么?
感谢帮助!
作为constexpr
函数使用的constexpr
函数需要在使用时定义。但是,当你使用 constStrLength()
来 define length
它只是 declared: 成员函数定义在 class 定义实际上只在 class 定义中 声明 !他们的定义在 class 定义之后立即可用,即在右括号之后非正式地说。
解决方法是在使用前定义 constStrLength()
,例如,作为非成员函数或通过在基础 class.