【发布时间】:2020-02-05 08:05:09
【问题描述】:
我有以下代码:
#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
^~~~~~~~
【问题讨论】:
-
你用的是什么编译器?它的什么版本?编译时你给编译器什么标志或选项?你得到什么错误?为什么你认为问题出在
std::tuple?最后,在创建minimal reproducible example 时,请尽量确保它不包含任何其他不相关的错误(例如缺少分号)。 -
根据clang,问题出在:
res[i] = {i, strings[i], bounds[i]}; -
你忘了;在变量声明之后。还要确保包含
<string>,<string_view>可能只是前向声明它。 -
元组赋值运算符在 c++20 之前不是 constexpr:en.cppreference.com/w/cpp/utility/tuple/operator%3D