c++ - 为什么我不能在constexpr lambda函数中使用std::tuple

标签 c++ c++17 stdtuple

我有以下代码:

#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的原因是什么?

我正在使用
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
        ^~~~~~~~

最佳答案

tuplepair在C++ 17中都没有constexpr分配。

但是,即使是包含值对的琐碎结构也能胜任。如果需要,您可能需要实现自己的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将来的标准来进行错误编码

关于c++ - 为什么我不能在constexpr lambda函数中使用std::tuple,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60071381/

相关文章:

c++ - 枚举型函数返回错误 "was not declared in this scope"

c++ - windows类型到linux

c++ - 如何递归元组?

c++ - 使结构表现得像 std::tuple

c++ - 返回元组的可变参数模板

c++ - 对指针使用输出流重载运算符

android - 在 OpenCV android 应用程序中启用 "libc++_shared.so"

c++ - 非类型模板参数可以是 "void*"类型吗?

c++ - 如何将模板 lambda 传递给函数并将其与不同类型一起使用

c++ - 折叠表达式 : iterate over variadic template type parameter to check compile-time conditions on the comprising types