Determine `constexpr` execution - during compilation or at runtime?

给你一囗甜甜゛ 提交于 2019-12-03 09:02:58

问题


Is there a way to achieve different behaviour of a constexpr function in the compilation phase and at runtime?

Consider the following example (using a theoretical feature from D: static if):

constexpr int pow( int base , int exp ) noexcept
{
    static if( std::evaluated_during_translation() ) {
        auto result = 1;
        for( int i = 0 ; i < exp ; i++ )
            result *= base;
        return result;
    } else { // std::evaluated_during_runtime()
        return std::pow( base , exp );
    }
}

If not, is there a way to restrict constexpr to be compile-time only?


回答1:


No, there is no such way.

Sorry.

N3583 is a paper proposing changes to allow what you are asking for.



来源:https://stackoverflow.com/questions/28683234/determine-constexpr-execution-during-compilation-or-at-runtime

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