【问题标题】:C++ parse errors when using template class使用模板类时 C++ 解析错误
【发布时间】:2021-12-27 00:59:39
【问题描述】:

我有一个学校作业,我必须编写一个模板类来存储整数列表的最小值。运行它时,我得到解析错误,但我不明白为什么。有人可以解释为什么我会收到这些错误吗?

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;

错误

ListMin.hpp:4: parse error before `...'
ListMin.hpp:7: parse error before `...'
ListMin.hpp:14: parse error before `<'

提前致谢

【问题讨论】:

  • 以这种不寻常的方式使用enum,而不是直接使用constexpr int,有什么特别的原因吗?
  • 即使在 C++17 中,这也不是很正确,但我会把它留给更擅长参数包的人来解释。
  • 出于普遍的兴趣,您使用的是什么编译器和版本?我找不到能重现您的确切错误消息的消息。
  • @user4581301 不知道具体情况,但正如我的教授刚刚在电子邮件中告诉我们的那样:它和我一样古老。似乎并非校园里的所有计算机课程都有最新的编译器。

标签: c++ parse-error template-classes


【解决方案1】:

第一个问题:你需要扩展others包。

Clang 预先告诉它:

<source>:9:27: error: enumerator value contains unexpanded parameter pack 'others'
    enum : long { value = std::min(first, ListMin<others>::value) };
                          ^                       ~~~~~~

解决方案:

enum : long { value = std::min(first, ListMin<others...>::value) };
//                                                  ^~~

第二个问题:std::min 要求参数具有相同的类型。 (目前有int 与未命名的enum)。

enum : long { value = std::min(first, int(ListMin<others...>::value)) };
//                                    ^~~~                         ^

更好的解决方案是使用std::min({1, 2, 3}),即自C++14 以来的constexpr(就像您已经使用的std::min(1, 2))。

或者至少,删除古老的 C 风格的未命名枚举并将其替换为 static constexpr int value = ...;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2014-01-06
    • 1970-01-01
    • 2021-01-12
    • 2017-05-12
    • 2016-04-21
    相关资源
    最近更新 更多