计算阶乘的 C++17 倍表达式中的错误
Error in C++17 fold expression to calculate factorial
下面的程序在 g++ 和 clang 中都给出了错误...
#include <iostream>
#include <utility>
using namespace std;
//Since C++17 one can use fold expression to calculate factorial:
template <class T, T N, class I = std::make_integer_sequence<T, N>>
struct factorial;
template <class T, T N, T... Is>
struct factorial<T,N,std::index_sequence<T, Is...>> {
static constexpr T value = (static_cast<T>(1)* ... *(Is + 1));
};
int main(int argc, char** argv) {
std::cout << factorial<int, 5>::value << std::endl;
return 0;
}
gcc 中列出的错误如下:
error: type/value mismatch at argument 1 in template parameter list for 'template<long unsigned int ..._Idx> using index_sequence = std::integer_sequence<long unsigned int, _Idx ...>'
24 | struct factorial<T,N,std::index_sequence<T, Is...>> {
| ^~~
note: expected a constant of type 'long unsigned int', got 'T'
error: template argument 3 is invalid
24 | struct factorial<T,N,std::index_sequence<T, Is...>> {
| ^~
In function 'int main(int, char**)':
error: incomplete type 'factorial<int, 5>' used in nested name specifier
31 | std::cout << factorial<int, 5>::value << std::endl;
| ^~~~~
叮当错误如下:
error: template argument for non-type template parameter must be an expression
struct factorial<T,N,std::index_sequence<T, Is...>> {
^
D:Programsmsys64mingw64includec++10.1.0utility:344:22: note: template parameter is declared here
template<size_t... _Idx>
^
main.cpp:32:18: error: implicit instantiation of undefined template 'factorial<int, 5, std::integer_sequence<int, 0, 1, 2, 3, 4> >'
std::cout << factorial<int, 5>::value << std::endl;
^
main.cpp:22:8: note: template is declared here
struct factorial;
^
许多网站都显示了此示例。
请人帮我纠正。
您对结果对象使用了错误的类型。
std::index_sequence
是一个模板,只接受一包std::size_t
。它不接受类型参数,因为类型是固定的。它是std::integer_sequence<std::size_t, Ints...>
的别名模板。
因此,您尝试指定类型,因为它是std::index_sequence<T,...>
中的第一个参数是错误的。
你想要的是更一般的类型特征std::integer_sequence
,让你的专业化变成这个
template <class T, T N, T... Is>
struct factorial<T,N,std::integer_sequence<T, Is...>> {
static constexpr T value = (static_cast<T>(1)* ... *(Is + 1));
};
实时代码示例
相关文章:
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 错误:表达式必须是可修改的 I值
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 错误:表达式不能用作函数
- C++/错误:表达式必须具有整数或无作用域枚举类型
- 错误表达式必须是插入函数(二叉树 C++)中的可修改 Ivalue
- 合并排序错误 - 表达式必须具有常量值
- 数组声明中的错误:表达式必须具有常量值
- 错误:表达式列表在初始化器[-fpermissive] Double Paycalc(p,yir,y)中被视为复合表达式
- 错误:表达式不能用作函数
- 我该如何解决此错误:表达式必须具有恒定值.环境是2013年
- 错误:表达式必须是可修改的LVALUE
- 错误:表达式必须具有指向类C++的指针
- 错误:表达式不能用作函数
- 错误:表达式必须具有积分或未引人注目的枚举类型
- 参数化sc_lv时报告错误(表达式必须具有常量值)
- 无法使用函数变量?错误表达式必须具有类类型
- 错误:表达式必须具有类类型
- 错误:表达式不能用作函数.如何删除它
- C++ - 错误:表达式必须具有指向对象的指针类型