为什么我不能在constexpr lambda函数中使用std :: tuple [英] Why can't I use a std::tuple in a constexpr lambda function

查看:150
本文介绍了为什么我不能在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,此代码无法编译.我不能在lambda函数中使用std::tuple的原因是什么?

but this code does not compile due to the std::tuple. What is the reason I can't use std::tuple inside a lambda function?

我正在使用

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中,tuplepair都没有constexpr分配.

Neither tuple nor pair have constexpr assignment in C++17.

但是,即使是包含值对的琐碎结构也能胜任.如果需要,您可能需要实现自己的constexpr兼容结构.没有绒毛的普通版本,您需要:

But even a trivial struct containing pair of values would do the job. You may want to implement own constexpr-compatible structure if required. Trivial version without fluff you need:

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作为未来标准的方式进行错误编码

It's possible to arrangle code the way it would use tuple for future standard

这篇关于为什么我不能在constexpr lambda函数中使用std :: tuple的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆