计算阶乘的 C++17 倍表达式中的错误

Error in C++17 fold expression to calculate factorial

本文关键字:错误 表达式 C++17 阶乘 计算      更新时间:2023-10-16

下面的程序在 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));
};

实时代码示例