May 26, 2015

[constexpr][study note] C++ at Compile Time

C++ at Compile Time

  • constexpr function must have a throw
  • Declare unresolved extern const char*
  • Reference unresolved extern in throw

  • extern const char* compile11_bin_invoked_at_runtime;
    template lt;typename T = std::uint32_t>
    constexpr T compile11_bin(
    constexpr_txt t,
    std::size_t i = 0, // index
    std::size_t b = 0, // bit count
    T x = 0) // accumulator
    {
    return
    i >= t.size() ? x : // end recursion
    b >= std::numeric_limitslt;T>::digits ?
    throw std::overflow_error("Too many bits!") :
    t[i] == ',' ? compile11_binlt;T>(t, i+1, b, x) :
    t[i] == '0' ? compile11_binlt;T>(t, i+1, b+1, (x*2)+0) :
    t[i] == '1' ? compile11_binlt;T>(t, i+1, b+1, (x*2)+1) :
    throw std::domain_error( // Only '0', '1', and ','
    compile11_bin_invoked_at_runtime);
    }
    
    int main()
    {
    auto mask = // lt;- Not constexpr!
    compile11_binlt;std::uint8_t>("1110 0000");
    assert(mask == 0xE0);
    return 0;
    }
    

    Compile-Time Floating Point

    No comments:

    Post a Comment

    Note: Only a member of this blog may post a comment.