• Source
    1. #include <iostream>
    2.  
    3.  
    4. /**
    5.  * @brief Constexpr class.
    6.  */
    7. class ConstValue
    8. {
    9. private:
    10. // the value to store
    11. const int m_value;
    12.  
    13. public:
    14. // explicit constructor
    15. constexpr explicit ConstValue(int value) :
    16. m_value(value)
    17. {
    18. }
    19. // explicit backconversion (for output etc.)
    20. constexpr explicit operator const int(void)
    21. {
    22. return m_value;
    23. }
    24. };
    25.  
    26.  
    27. // global variable test
    28. //
    29. static constexpr const ConstValue VALUE = (ConstValue)1; // works
    30. static const int VALUEINT = (int)VALUE; // works
    31. static const char* STRING = "STRING"; // works
    32.  
    33.  
    34. // class member global variable test
    35. //
    36. class Foo
    37. {
    38. public:
    39. // static constant member variables
    40. static constexpr const ConstValue VALUE = (ConstValue)2; // fails
    41. static const int VALUEINT = (int)VALUE; // works
    42. static constexpr const char* STRING = "Foo::STRING"; // fails
    43.  
    44. // function access tests
    45. static const ConstValue value(void) {return VALUE;} // fails
    46. static const int valueInt(void) {return (int)VALUE;} // fails
    47. static const char* string(void) { return STRING; } // fails
    48. };
    49.  
    50.  
    51. /**
    52.  * @brief Main function.
    53.  */
    54. int main()
    55. {
    56. // integer output
    57. std::cout << "VALUE = " << (int)VALUE << " (should be 1)\n";
    58. std::cout << "VALUEINT = " << VALUEINT << " (should be 1)\n";
    59. std::cout << "Foo::VALUE = " << (int)Foo::VALUE << " (should be 2)\n";
    60. std::cout << "Foo::VALUEINT = " << Foo::VALUEINT << " (should be 2)\n";
    61. std::cout << "Foo::value() = " << (int)Foo::value() << " (should be 2)\n";
    62. std::cout << "Foo::valueInt() = " << (int)Foo::valueInt() << " (should be 2)\n";
    63.  
    64. // string output (beware of nullptrs)
    65. const char *ptr;
    66. ptr = STRING; std::cout << "STRING = " << (ptr?ptr:"<nullptr>") << " (should be STRING)\n";
    67. ptr = Foo::STRING; std::cout << "Foo::STRING = " << (ptr?ptr:"<nullptr>") << " (should be Foo::STRING)\n";
    68. ptr = Foo::string(); std::cout << "Foo::string() = " << (ptr?ptr:"<nullptr>") << " (should be Foo::STRING)\n";
    69.  
    70. // done
    71. return 0;
    72. }
    73.