gpt4 book ai didi

C++ string.length() 不可用于常量表达式

转载 作者:太空狗 更新时间:2023-10-29 19:42:59 27 4
gpt4 key购买 nike

使用 C++。我有以下代码,我正在尝试使用模板传递函数 foo 的二维数组的大小。但是,问题是传递给模板的大小必须保持不变。任何指示都有帮助,谢谢。

#include <iostream>
using namespace std;

template <size_t r, size_t c>
bool foo(bool (&arr)[r][c])
{
cout << "foo\n";
}

int main() {
string s = "abcd";
const size_t N = s.length(); //is this incorrect?
bool arr[N][N];
foo<N, N>(arr);
return 0;
}

似乎不能使用 string.length() 或 string.size() 来初始化常量。当我尝试编译时出现错误:

main.cpp: In function ‘int main()’:
main.cpp:14:6: error: the value of ‘N’ is not usable in a constant expression
foo<N, N>(arr);
^
main.cpp:12:15: note: ‘N’ was not initialized with a constant expression
const size_t N = s.length();
^
main.cpp:14:9: error: the value of ‘N’ is not usable in a constant expression
foo<N, N>(arr);
^
main.cpp:12:15: note: ‘N’ was not initialized with a constant expression
const size_t N = s.length();
^
main.cpp:14:15: error: no matching function for call to ‘foo<N, N>(bool [N][N])’
foo<N, N>(arr);
^
main.cpp:5:6: note: candidate: template<long unsigned int r, long unsigned int c> bool foo(bool (&)[r][c])
bool foo(bool (&arr)[r][c])
^~~
main.cpp:5:6: note: template argument deduction/substitution failed:
main.cpp:14:15: error: the value of ‘N’ is not usable in a constant expression
foo<N, N>(arr);
^
main.cpp:12:15: note: ‘N’ was not initialized with a constant expression
const size_t N = s.length();
^
main.cpp:14:15: note: in template argument for type ‘long unsigned int’
foo<N, N>(arr);
^
main.cpp:14:15: error: the value of ‘N’ is not usable in a constant expression
main.cpp:12:15: note: ‘N’ was not initialized with a constant expression
const size_t N = s.length();
^
main.cpp:14:15: note: in template argument for type ‘long unsigned int’
foo<N, N>(arr);
^

最佳答案

const size_t N = s.length(); //is this incorrect?

它的格式正确并且具有明确定义的行为。

It seems that string.length() or string.size() cannot be used to initialize a constant.

当然可以。它可用于初始化运行时常量变量,这就是您的 N

但它不能用于初始化编译时常量。您在需要编译时常量表达式的上下文中使用运行时常量变量。

一个简单的修复:改用字符串文字的大小:

// could use constexpr too
const unsigned long N = std::size("abcd") - 1;

注意 -1 以说明空终止符。

关于C++ string.length() 不可用于常量表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127918/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com