c++ - C++11 中的 constexpr if-then-else

标签 c++ c++11 perfect-forwarding

我在模板化代码库的某些部分需要 constexpr if,但由于它在 C++11 中不可用,所以我决定提出自己的更简单的 constexpr if-then 版本-否则。

下面是我的 constexpr if-then-else 实现。我不完全确定它是否正确,并且无法在任何地方找到任何适当解释它的相关内容。如果有人可以验证这一点,和/或可能指出替代实现,那将非常有帮助。

template <typename T, typename F>
constexpr F static_ite(std::false_type, T &&, F &&f) { return f; }

template <typename T, typename F>
constexpr T static_ite(std::true_type, T &&t, F &&) { return t; }

template <bool cond, typename T, typename F>
constexpr auto static_ite(T &&t, F &&f)
    -> decltype(static_ite(std::integral_constant<bool, cond>{}, std::forward<T>(t), std::forward<F>(f)))
{
    return static_ite(std::integral_constant<bool, cond>{}, std::forward<T>(t), std::forward<F>(f));
}

我打算将其用作通用模板。任何帮助将不胜感激。

最佳答案

template <typename T, typename F>
constexpr typename std::decay<F>::type static_ite(std::false_type, T &&, F &&f) { return std::forward<F>(f); }

其他分支也类似。可以使用 std ref 或指针显式传递引用。

我发现更通用的调度也很有用:

template<std::size_t N, class...Ts>
nth_type<N,typename std::decay<Ts>::type...>
dispatch_nth(index_t<N>, Ts&&...ts);

(编写明显的助手)。

这可以让您在 2 个以上的分支上工作。

使用 auto lambda 参数,所有这些都变得更加出色;那是 它最早于实现早期实现。

关于c++ - C++11 中的 constexpr if-then-else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65644157/

相关文章:

c++ - OpenCV 捕获视频 Ubuntu 12.0.4

c++ - 复制整数位的最快方法

c++ - 尝试对对象数组进行排序时程序终止

c++ - 为什么 std::map::insert 在以下示例中失败?

c++ - 前进或 move 与否;如何确定在类的使用上下文中哪个是首选?

c++ - 从模板类型而不是参数获取转发类型

c++ - 这是初始化我的图书馆的合理方式吗?

c++ - 使用 c++11 线程返回结果的正确方法是什么?

c++ - 在 std::function 原型(prototype)中使用 'this' 指针

c++ - 为什么我的代码无法编译? (完美转发和参数包)