Why do we need the two definitions: integral constant expression and converted constant expression?

前端 未结 3 1996
春和景丽
春和景丽 2021-02-04 03:49

§5.19/3 in C++14 defines an integral constant expression and a converted constant expression:

An integral constant expression is an expression

3条回答
  •  面向向阳花
    2021-02-04 04:17

    Both definitions are needed because there are things you can do with one but not the other. And no, not every integral constant expression is really a converted constant expression. For the obvious example, a converted constant expression prohibits narrowing conversions, but an integral constant expression doesn't.

    Therefore I can't do this:

    enum x : char { a = 1024 };
    

    If, however the initializer for an enum allowed an integral constant expression, rather than a converted constant expression, precisely that would be allowed.

    As a Venn diagram, I'd draw the situation something like this:

    So, there is quite a bit of overlap between the two (probably more than this diagram implies) but each allows at least a few things the other doesn't. I've given an example of one item in each direction, but haven't tried to list the differences exhaustively.

    I'm not entirely convinced about user-defined conversions being prohibited for integral constant expressions though (and a quick test shows that the compilers I have handy at the moment allow them). That would give the situation as I originally wrote this answer, which would be more like this:

提交回复
热议问题