Static constexpr int vs old-fashioned enum: when and why?

前端 未结 3 1547
甜味超标
甜味超标 2020-12-15 03:53

This is maybe a basic question, but I cannot see the response by myself right now.

Consider the following code:

template
struct T {
            


        
3条回答
  •  情歌与酒
    2020-12-15 04:34

    I suspect it's legacy code.

    enum { value = (b ? 42 : 0) };
    

    is valid code in C++03 as well as C++11.

    static constexpr int value = (b ? 42 : 0);
    

    is valid only in C++11.

    Even more, is there any case for which one of them is not a viable solution?

    Both are viable solutions in C++11. The choice of which one to use depends on a team. It's going to be a matter of a policy decision.

    As the answer by SergeyA indicates, enum are true constants. You cannot ODR-use them. You can ODR-use a constexpr. Depending on which of these is desirable for your application, you can decide whether to use enums or constexprs.

提交回复
热议问题