May a compiler elide the evaluation of the “not-taken” branch in a constexpr function?

谁说我不能喝 提交于 2020-01-05 10:19:23

问题


While attempting to answer a question by Mehrdad, I concocted the little function below (in action at liveworkspace):

template <typename T, unsigned low, unsigned high>
static constexpr auto highest_index_in() ->
   typename std::enable_if<high >= low, unsigned>::type
{
   return low == high                 ? low :
          high == low + 1             ? (exists<T, high>() ? high : low) :
          exists<T, (high + low)/2>() ? highest_index_in<T, (high+low)/2, high>() :
                                        highest_index_in<T, low, (high+low)/2>();
} // highest_index_in

(where exists is O(1))

The compilation is extremely slow though (on liveworkspace), and attempting to use wide ranges fail utterly with compiler crashes ([0, ~0u] does not work...).

I believe I managed to implement the recursion correctly (I would be glad to be contradicted), and yet...

Thus the question: when evaluating the various ternary operators calls here, may the compiler elide the computation of the not-taken branch ?


回答1:


No, the compiler can not skip the evaluation of the not-taken branches of the ternary operator, because to do so means the compiler first has to establish there are no conflicting overloads and/or template specialisations in any of those branches possible that could render the program ill-formed. To do that determination, the compiler effectively has to instantiate the templates used on the branches and perform overload resolution on the functions.



来源:https://stackoverflow.com/questions/14213754/may-a-compiler-elide-the-evaluation-of-the-not-taken-branch-in-a-constexpr-fun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!