Why don't static member variables play well with the ternary operator?

后端 未结 3 1213
余生分开走
余生分开走 2020-12-31 05:07

Here\'s the deal. I have a static class which contains several static functions used for getting input. The class contains a private static member variable for indicating wh

相关标签:
3条回答
  • 2020-12-31 05:47
    class Test {
        static const int GOOD = 0;
        static const int BAD = 1;
    };
    

    These are only declarations; they are not definitions. You need to provide definitions of the static member variables, outside of the definition of the class, in one of your .cpp files:

    const int Test::GOOD;
    const int Test::BAD;
    

    Alternatively, for integer constants, it is often more convenient to use an enum:

    class Test {
        enum { 
            GOOD = 0,
            BAD = 1 
        };
    };
    
    0 讨论(0)
  • 2020-12-31 05:52

    This is according to the C++ Standard. The ternary operator does constitute a single lvalue that will refer to either GOOD or BAD at runtime. The lvalue to rvalue conversion is not applied immediately to either the lvalue GOOD or BAD, and therefor you require a definition of GOOD and BAD.

    See the core language issue report http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#712 .

    As a workaround, you can apply explicit casts to int (which reads their values, thereby doing an lvalue to rvalue conversion) or use an operator that reads the value, like +:

    localStatus = (num > 2) ? +GOOD : +BAD;
    
    0 讨论(0)
  • 2020-12-31 05:54

    Your code looks fine to me. And ideone agrees: see this link. But that's with gcc-4.3.4. However, my gcc-4.4.0 doesn't accept it. So whatever the reason, it's not obvious.

    Edited to add: The following variant compiles under gcc-4.4.0:

    int localStatus = 42 ? GOOD : BAD;
    

    Reminder: the following code doesn't compile:

    int localStatus = (num == 42) ? GOOD : BAD;
    

    So somebody has screwed up somewhere.

    0 讨论(0)
提交回复
热议问题