fork download
  1. #include <iostream>
  2.  
  3. // use the preprocessor
  4. #define PUBLIC_CONST( Type, Name, Initial_value ) \
  5.   public: const Type& Name = Name##_ ; \
  6.   private: Type Name##_ = Initial_value ;\
  7.   public:
  8.  
  9. // or use a templated type holder
  10. template < typename C, typename T > struct public_const_
  11. {
  12. operator const T& () const { return v ; }
  13. private:
  14. T v ;
  15. T& operator()() { return v ; }
  16. public_const_( const T& vv = T() ) : v(vv) {}
  17. friend C ;
  18. };
  19.  
  20. struct A
  21. {
  22. void foo() { count_ = 9999 ; value() = 99.99 ; }
  23.  
  24. PUBLIC_CONST( int, count, 1234 ) // preprocessor
  25.  
  26. template < typename T > using public_const = public_const_<A,T> ;
  27.  
  28. public_const<double> value = 12.34 ; // template
  29. };
  30.  
  31. int main()
  32. {
  33. A a ;
  34. std::cout << a.count << ' ' << a.value << '\n' ;
  35.  
  36. a.foo() ;
  37. std::cout << a.count << ' ' << a.value << '\n' ;
  38. }
  39.  
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
1234 12.34
9999 99.99