c++ - 为什么我不能在 constexpr lambda 函数中使用 std::tuple
问题描述
我有以下代码:
#include <string_view>
#include <array>
#include <tuple>
struct Variable
{
size_t index;
std::string_view name;
std::tuple<float, float> bounds;
};
constexpr std::array<Variable, 3> myarray = [](){
std::array<Variable, 3> res{};
std::array<std::string_view, 3> strings = {"myvar1", "myvar2", "myvar3"};
std::array<std::tuple<float, float>, 3> bounds = {{{0,1}, {1,2}, {2,3}}};
for (std::size_t i = 0; i != res.size(); ++i) {
res[i] = {i, strings[i], bounds[i]};
}
return res;
}();
但是由于std::tuple
. 我不能std::tuple
在 lambda 函数中使用的原因是什么?
我正在使用
c++ -Wall -Winvalid-pch -Wnon-virtual-dtor -Wextra -Wpedantic -std=c++17 -g -o main.o -c main.cpp
编译代码。
编译器版本为:gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)
我得到的错误是:
../main.cpp:53:3: error: call to non-constexpr function ‘<lambda()>’
}();
^
../main.cpp:44:51: note: ‘<lambda()>’ is not usable as a constexpr function because:
constexpr std::array<Variable, num_vars> xrt = [](){
^
../main.cpp:51:39: error: call to non-constexpr function ‘Variable& Variable::operator=(Variable&&)’
res[i] = {i, strings[i], bounds[i]};
^
../main.cpp:16:8: note: ‘Variable& Variable::operator=(Variable&&)’ is not usable as a constexpr function because:
struct Variable
^~~~~~~~
解决方案
在 C++17 中既没有tuple
也没有 constexpr 赋值。pair
但即使是包含一对值的简单结构也可以完成这项工作。如果需要,您可能希望实现自己的 constexpr 兼容结构。您需要的没有绒毛的简单版本:
struct Couple {
float a, b;
};
struct Variable
{
size_t index;
std::string_view name;
Couple bounds;
};
constexpr std::array<Variable, 3> myarray = [](){
std::array<Variable, 3> res{};
std::array<std::string_view, 3> strings = {"myvar1", "myvar2", "myvar3"};
std::array<Couple, 3> bounds = {{{0,1}, {1,2}, {2,3}}};
for (std::size_t i = 0; i != res.size(); ++i) {
res[i] = {i, strings[i], bounds[i]};
}
return res;
}();
tuple
可以按照用于未来标准的方式排列代码
推荐阅读
- php - Laravel Nova 如何在文本字段中添加实时计数器
- office365 - BizTalk SharePoint 适配器和 SharePoint Online 更新 SharePoint 列表的权限
- xml - 如果属性存在于 xml 的 ref url 中,如何在 xslt 中选择条件?
- java - 使用 Gradle Kotlin DSL 包含脚本
- r - 在多个变量上重复一个函数
- javascript - 为什么我的 HTTP 获取请求被多次调用?
- scala - DataFrame 到 RDD[(String, String)] 的转换
- laravel - 如何检查文件是否存在于laravel的外部服务器中?
- sql-server - 转换数据类型时 ssis 中的问题
- angular - 上下文菜单事件打开默认上下文菜单并触发事件