Is constexpr really needed?

后端 未结 6 2221
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 14:35

I have been looking at the new constexpr feature of C++ and I do not fully understand the need for it.

For example, the following code:

         


        
6条回答
  •  醉梦人生
    2020-12-03 14:46

    Something you can do with constexpr that you can not do with macros or templates is parsing /processing strings at compile time: Compile time string processing (changing case, sorting etc.) with constexpr. As a small excerpt from the preceding link, constexpr allows one to write code such as:

    #include "my_constexpr_string.h"
    int main()
    {
       using namespace hel;
       #define SDUMP(...) static_assert(__VA_ARGS__, "")
    
       SDUMP(tail("abc") == "bc");
       SDUMP( append("abc", "efgh") == "abcefgh" );
       SDUMP( prepend("abc", "efgh") == "efghabc" );
       SDUMP( extract<1,3>("help") == "el" );
       SDUMP( insert<1>("jim", "abc") == "jabcim" );
       SDUMP( remove("zabzbcdzaz", 'z') == "abbcdazzzz" );
       SDUMP( erase("z12z34z5z", 'z') == "12345"  );
       SDUMP( map("abc", ToUpper()) == "ABC" );
       SDUMP( find("0123456777a", '7') == 7 );
       SDUMP( isort("03217645") == "01234567");  
    }
    

    As an example of when this could be useful, it could facilitate the compile time computation/construction of certain parsers and regular expression finite-state-machines that are specified with literal strings. And the more processing you can push off to compile time, the less processing you do at run time.

提交回复
热议问题