如何 return constexpr 的元组

how to return a tuple for a constexpr

找了一段时间,还是不太明白。有人可以告诉我如何 return 常量表达式中的元组吗?这是代码:

#include <tuple>
constexpr std::tuple<int, int> ret2 () {
    int a = 1;
    int b = 2;
    return std::make_tuple(a, b);
}

constexpr int ret1 () {
    int a = 0;
    int b = 0;
    std::tie(a, b) = ret2();
    return a + b;
}

constexpr auto tmp = ret1();

clang++ -std=c++14 -o 测试 test.cpp

test.cpp:15:16: error: constexpr variable 'tmp' must be initialized by a constant expression
constexpr auto tmp = ret1();
               ^     ~~~~~~
test.cpp:11:17: note: non-constexpr function
      'operator=<std::__1::tuple<int, int>, void>' cannot be used in a constant expression
        std::tie(a, b) = ret2();
                       ^
test.cpp:15:22: note: in call to 'ret1()'
constexpr auto tmp = ret1();
                     ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/tuple:899:9: note: 
      declared here
        operator=(_Tuple&& __t) _NOEXCEPT_((is_nothrow_assignable<base&...
        ^
1 error generated.

clang --version

Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin17.0.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

我已经尝试将其更改为 std::tuple<int&, int&>,并使用 std::ref,等等...我似乎无法找到正确的顺序。

此外,调用 std::get 2x 会导致代码冗长并且在运行时可能造成浪费。有没有办法通过一次调用获得两个值 - 如图所示?

你的 ret1 的实现只需要 std::get:

constexpr int ret1() {
    return std::get<0>(ret2());
}

Demo.

您不能使用 std::tuple::operator=,因为它不是 constexpr。您的示例可以转换为:

constexpr std::tuple<int, int> ret2 () {
    int a = 1;
    int b = 2;
    return std::make_tuple(a, b);
}

constexpr int ret1 () {
    constexpr auto t = ret2();
    return std::get<0>(t) + std::get<1>(t);
}

constexpr auto tmp = ret1();

和原来的一样,虽然我不确定它是否满足你的实际需求。