gpt4 book ai didi

c++ - 带有参数包的类模板的构造函数给出 C3520 错误

转载 作者:行者123 更新时间:2023-11-27 23:49:33 24 4
gpt4 key购买 nike

试验一些模板及其用途:

我在这里研究这个简单的结构:

template<typename T, size_t n>  // templated but not variadic
struct myArray {
static const size_t SIZE = n;
T arr_[SIZE];

myArray() {} // Default Constructor

template<class... U> // Initialization Constructor
myArray( U pack... ) { // Templated with variadic parameters of
// type U = T upto SIZE = n;
arr_ = pack...;
}
};

我想以这种方式或类似方式使用它:

int main() {
myArray<char, 6> arr1{ 'a', 'b', 'c', 'd', 'e', 'f' };
myArray<int, 4> arr2{ 1, 2, 3, 4 };

// Or like this:
myArray<char, 6> arr1 = { 'a', 'b', 'c', 'd', 'e', 'f' };
myArray<int, 4> arr2 = { 1, 2, 3, 4 };
}

在 visual studio 2017RC 中,我不断收到此编译器错误:

1>------ Build started: Project: PracticeMath, Configuration: Debug Win32 ------
1>PracticeMath.cpp
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(19): error C3520: 'U': parameter pack must be expanded in this context
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(22): note: see reference to class template instantiation 'myArray<T,n>' being compiled
1>c:\users\skilz80\documents\visual studio 2017\projects\practicemath\practicemath\practicemath.cpp(41): fatal error C1903: unable to recover from previous error(s); stopping compilation
1>Done building project "PracticeMath.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

不确定我在这里遗漏了什么或在初始化构造函数中做什么。

最佳答案

编写该构造​​函数的一种可能方法是

template <class ... U>
myArray( U ... pack ) : arr_ { pack... }
{ }

代码中有两个错误

(1) ...声明包名前;所以

myArray ( U pack ... )
// ..............^^^ wrong

myArray ( U ... pack )
// .........^^^ correct

(2) 有很多模式可以使用可变参数包,但是

arr_ = pack...;

不正确。

将可变参数包与 C 风格数组一起使用的通常方法是在初始化中;即,在初始化列表中使用构造函数。

所以

myArray( U ... pack ) : arr_ { pack... }
// .....................^^^^^^^^^^^^^^^^

但是请注意,像这样的构造函数是危险的,因为没有检查包中元素的数量(如果大于 SIZE,则程序的行为未定义(并且这通常会变成:程序崩溃。避免这个问题的一个简单方法是在构造函数的主体中添加一个 static_assert();类似于

template <class ... U>
myArray( U ... pack ) : arr_ { pack... }
{ static_assert( sizeof...(U) <= N , "too much values" ); }

关于c++ - 带有参数包的类模板的构造函数给出 C3520 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47492334/

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