我在模板化代码库的某些部分需要 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 个以上的分支上工作。
关于c++ - C++11 中的 constexpr if-then-else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65644157/