【问题标题】:How can I mimic passing a std::pair as a template argument to a function in C++17?如何模拟将 std::pair 作为模板参数传递给 C++17 中的函数?
【发布时间】:2020-06-07 08:21:35
【问题描述】:

之前,我问过一个关于在编译时评估接收 std::pair 的函数的问题:

Why can I evaluate a function receiving a std::pair at compile-time, but not assert it?

这似乎在 C++17 中是不可能的,但在 C++20 中是可能的。现在,我正在寻找是否有一种方法可以模拟将 std::pair 传递给函数?理想情况下,我不会使用参数包,因为我想让用户清楚地知道这些值是成对出现的。

【问题讨论】:

    标签: c++ algorithm templates c++17 metaprogramming


    【解决方案1】:

    是的,这是可能的。只需创建一个编译时间对类型:

    template <auto First, auto Second>
    struct pair
    {
        static constexpr auto first = First;
        static constexpr auto second = Second;
    };
    

    我们的元组创建也突然变得更干净了:

    template<typename... Pairs>
    constexpr auto foo() noexcept
    {
        static_assert(((Pairs::second - Pairs::first >= 0) && ...));
        return std::tuple((Pairs::second - Pairs::first)...);
    }
    

    Here 是一个完整的例子。

    【讨论】:

    • 为什么不&lt;auto First, auto Second&gt;?毕竟,这个问题被标记为 C++17。
    • @NicolBolas 实际上是因为我忘记了我们可以做到这一点。虽然行为略有不同,因为两个参数可以有不同的类型。
    • 而且整数提升规则如果意外传递了一个无符号值也会让人头疼。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多