Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

c++ - Constexpr if-then-else in C++11

I require constexpr if in some part of my templated codebase, but since it is not available in C++11, I decided to come up with my own version of a simpler constexpr if-then-else.

Below is my implementation of constexpr if-then-else. I am not entirely sure if it is correct, and was unable to find any relevant content anywhere which suitably explains it. It would be really helpful if someone could verify this, and/or possibly point out alternative implementations.

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));
}

I intend to use it as a generic template. Any help would be appreciated.

question from:https://stackoverflow.com/questions/65644157/constexpr-if-then-else-in-c11

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm going to assume you want the function to return a reference to whatever you give it; if you instead want a copy, refer to Yakk's answer.


The return types of the first two overloads should be rvalue references, and you should std::forward when you return from them.

The long decltype could be shortened to typename std::conditional<cond, T &&, F &&>::type.

Everything else looks good to me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...