Determine `constexpr` execution - during compilati

2019-03-12 18:37发布

问题:

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.