我如何模拟将 std::pair 作为模板参数传递给 C++17 中的函数?
How can I mimic passing a std::pair as a template argument to a function in C++17?
之前,我问了一个关于评估在编译时接收 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 传递给函数?理想情况下,我不会使用参数包,因为我想让用户清楚这些值是成对出现的。
是的,这是可能的。只需创建一个 编译时对 类型:
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 是一个完整的例子。
之前,我问了一个关于评估在编译时接收 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 传递给函数?理想情况下,我不会使用参数包,因为我想让用户清楚这些值是成对出现的。
是的,这是可能的。只需创建一个 编译时对 类型:
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 是一个完整的例子。