[英]C++ parse errors when using template class
I have a school assignment where I have to code a template class that would store the minimum of a list of ints.我有一个学校作业,我必须编写一个模板类来存储整数列表中的最小值。 When running it, I get parse errors but I don't understand why.
运行它时,我收到解析错误,但我不明白为什么。 Could someone explain why I'm getting these errors?
有人可以解释为什么我会收到这些错误吗?
ListMin.hpp ListMin.hpp
template <int ... list>
class ListMin;
template <int first, int ... others>
class ListMin <first, others ...> {
public:
enum : long { value = std::min(first, ListMin<others>::value) };
};
template <int first>
class ListMin <first> {
public:
enum : long { value = first };
};
Main.cpp主程序
std::cout << "min( [ 1, -5, 3 ] ) = " << ListMin< 1, -5, 3 >::value << std::endl;
The errors错误
ListMin.hpp:4: parse error before `...'
ListMin.hpp:7: parse error before `...'
ListMin.hpp:14: parse error before `<'
Thanks in advance提前致谢
First problem: you need to expand the others
pack.第一个问题:你需要扩展
others
包。
Clang tells it up front: Clang 预先告诉它:
<source>:9:27: error: enumerator value contains unexpanded parameter pack 'others'
enum : long { value = std::min(first, ListMin<others>::value) };
^ ~~~~~~
Solution:解决方案:
enum : long { value = std::min(first, ListMin<others...>::value) };
// ^~~
Second problem: std::min
requires the arguments to have the same type.第二个问题:
std::min
要求参数具有相同的类型。 (Currently have int
vs an unnamed enum
). (目前有
int
与未命名的enum
)。
enum : long { value = std::min(first, int(ListMin<others...>::value)) };
// ^~~~ ^
A much better solution would be to use std::min({1, 2, 3})
, which is constexpr
since C++14 (just like std::min(1, 2)
, which you already use).更好的解决方案是使用
std::min({1, 2, 3})
,这是自 C++14 以来的constexpr
(就像std::min(1, 2)
,你已经使用)。
Or at least, drop the archaic C-style unnamed enum and replace it with static constexpr int value = ...;
或者至少,删除陈旧的 C 风格未命名枚举并将其替换为
static constexpr int value = ...;
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.