【问题标题】:how to return a tuple for a constexpr如何为 constexpr 返回一个元组
【发布时间】:2017-10-25 22:48:14
【问题描述】:

找了一阵子,还是没搞明白。有人可以告诉我如何以常量表达式返回元组。代码如下:

#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 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&lt;int&amp;, int&amp;&gt;,并使用std::ref 等...我似乎无法找到正确的序列。

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

【问题讨论】:

    标签: c++ c++14 constexpr stdtuple


    【解决方案1】:

    您不能使用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();
    

    它与原版的功能相同,但我不确定它是否满足您的实际需求。

    【讨论】:

    • constexpr auto tmp = ret1(); 不直接使用任何operator=:它是一个初始化,而不是一个赋值表达式。
    • 我更改了代码以显示对这两个值的需求。在我的实际用例中,我需要这两个值,它们都有助于生成 constexpr 结果。
    • 是否可以一次调用?
    • @nachum:已更新。无论如何,它是constexpr,所以调用它两次并不是什么大不了的事
    • 完美。谢谢!
    【解决方案2】:

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

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

    Demo.

    【讨论】:

    • 我更改了代码以显示对这两个值的需求。在我的实际用例中,我需要这两个值,它们都有助于生成 constexpr 结果。
    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    相关资源
    最近更新 更多