c++ - 可变参数模板折叠程序在 gcc9 中失败
问题描述
我使用 g++ 8.3 使用 -std=c++14 和 -std=c++1z 使以下程序按预期工作。但是,当我升级到 g++ 9.1 时,它仅在 -std=c++14 时有效,但不适用于更高版本。
#include <iostream>
using namespace std;
#if __cplusplus >= 201500L // C++17 or higher
template <typename... Args>
auto sum(Args&&... args)
{
return (0 + args);// + ... );
}
#elif __cplusplus >= 201402L // C++14
auto sum() { return 0; }
template <typename T>
auto sum(T&& t) { return t; }
template <typename T, typename... Rest>
auto sum(T&& t, Rest&&... r)
{
return t + sum(forward<Rest>(r)...);
}
#else
#error "***You need C++14 or higher to compile this program***"
#endif
int main()
{
cout << sum() << " result of 2 + 3=>" << sum(2, 3) <<
" result of 12+15+18=>" << sum(12, 15, 18) << "\n";
#if __cplusplus >= 201500L // C++17 or higher
cout << "Compiled as C++17 program\n";
#else
cout << "Compiled as C++14 program\n";
#endif
}
当我使用 -std=c++1z、c++17 或 c++2a 时,g++ 9.1 生成以下错误消息(及其许多同级):
In function 'auto sum(Args&& ...)':
error: parameter packs not expanded with '...':
12 | return (0 + args);// + ... );
| ~~~^~~~~~~
note: 'args'
In function 'int main()':
error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'void')
32 | cout << sum() << " result of 2 + 3=>" << sum(2, 3) <<
| ~~~~ ^~ ~~~~~
| | |
| | void
| std::ostream {aka std::basic_ostream<char>}
解决方案
推荐阅读
- javascript - 如何在函数内部返回函数?(如 p5.js createVector)
- c++ - 为什么这些程序被允许传递一个非常量变量而我不能?
- python - 尝试安装 chat-replay-downloader 导致“没有模块名为打字”
- reactjs - 当输入不聚焦时使输入标签保持不变
- linux - 进程退出后内存仍在使用
- c++ - 为什么我在进行单元测试时 Visual Studio 会给出未解决的外部符号错误?
- mysql - MySQL UNION ALL 多重使用优化
- rest - 使用不同的 WebAPI 将相关数据输入数据库
- c# - 定义不需要访问器的数据类型(单属性类)
- python - 带或不带括号的对象属性标注信息