#include <iostream>
// use the preprocessor
#define PUBLIC_CONST( Type, Name, Initial_value ) \
public: const Type& Name = Name##_ ; \
private: Type Name##_ = Initial_value ;\
public:
// or use a templated type holder
template < typename C, typename T > struct public_const_
{
operator const T& () const { return v ; }
private:
T v ;
T& operator()() { return v ; }
public_const_( const T& vv = T() ) : v(vv) {}
friend C ;
};
struct A
{
void foo() { count_ = 9999 ; value() = 99.99 ; }
PUBLIC_CONST( int, count, 1234 ) // preprocessor
template < typename T > using public_const = public_const_<A,T> ;
public_const<double> value = 12.34 ; // template
};
int main()
{
A a ;
std::cout << a.count << ' ' << a.value << '\n' ;
a.foo() ;
std::cout << a.count << ' ' << a.value << '\n' ;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKLy8gdXNlIHRoZSBwcmVwcm9jZXNzb3IKI2RlZmluZSBQVUJMSUNfQ09OU1QoIFR5cGUsIE5hbWUsIEluaXRpYWxfdmFsdWUgKSBcCiAgICBwdWJsaWM6IGNvbnN0IFR5cGUmIE5hbWUgPSBOYW1lIyNfIDsgXAogICAgcHJpdmF0ZTogVHlwZSBOYW1lIyNfID0gSW5pdGlhbF92YWx1ZSA7XAogICAgcHVibGljOgoKLy8gb3IgdXNlIGEgdGVtcGxhdGVkIHR5cGUgaG9sZGVyCnRlbXBsYXRlIDwgdHlwZW5hbWUgQywgdHlwZW5hbWUgVCA+IHN0cnVjdCBwdWJsaWNfY29uc3RfCnsKICAgIG9wZXJhdG9yIGNvbnN0IFQmICgpIGNvbnN0IHsgcmV0dXJuIHYgOyB9CiAgICBwcml2YXRlOgogICAgICAgIFQgdiA7CiAgICAgICAgVCYgb3BlcmF0b3IoKSgpIHsgcmV0dXJuIHYgOyB9CiAgICAgICAgcHVibGljX2NvbnN0XyggY29uc3QgVCYgdnYgPSBUKCkgKSA6IHYodnYpIHt9CiAgICAgICAgZnJpZW5kIEMgOwp9OwoKc3RydWN0IEEKewogICAgdm9pZCBmb28oKSB7IGNvdW50XyA9IDk5OTkgOyB2YWx1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