Populate An Array Using Constexpr at Compile-time

后端 未结 4 1788
[愿得一人]
[愿得一人] 2020-11-29 03:32

I would like to populate an array of enum using constexpr. The content of the array follows a certain pattern.

I have an enum separating ASCII character set into fou

4条回答
  •  佛祖请我去吃肉
    2020-11-29 04:10

    The way to do this in C++14 looks like this:

    #include 
    
    enum Type {
        Alphabet,
        Number,
        Symbol,
        Other,
    };
    
    constexpr ::std::array MagicFunction()
    {
       using result_t = ::std::array;
       result_t result = {Other};
       const result_t &fake_const_result = result;
       const_cast(fake_const_result[65]) = Alphabet;
       //....
       return result;
    }
    
    const ::std::array table = MagicFunction();
    

    No clever template hackery required any longer. Though, because C++14 didn't really undergo a thorough enough review of what did and didn't have to be constexpr in the standard library, a horrible hack involving const_cast has to be used.

    And, of course, MagicFunction had better not modify any global variables or otherwise violate the constexpr rules. But those rules are pretty liberal nowadays. You can, for example, modify all the local variables you want, though passing them by reference or taking their addresses may not work out so well.

    See my other answer for C++17, which allows you to drop some of the ugly-looking hacks.

提交回复
热议问题