Inpired by this answer I'm using the following solution for read-only member variables:
template <class T, class OWNER>
class readonly
{
friend OWNER;
public:
explicit readonly(const T &t) : m_t(t)
{
}
~readonly()
{
}
operator const T&() const
{
return m_t;
}
private:
T& operator =(const T &t)
{
m_t = t;
return m_t;
}
T m_t;
};
Which works great, to optimize performance a little I use it like this:
class A
{
public:
A()
{
}
~A()
{
}
#ifdef _DEBUG // DON'T USE THIS SWITCH, SEE ANSWERS BELOW!
readonly<int, A> m_x, m_y;
#else
int m_x, m_y;
#endif
};
However I would love to eliminate the precompiler switch which checks if we're doing a debug or release build... Does anyone see a solution using a macro or clever template trick?
EDIT: I've checked the performance in a loop, it generates about 15~20% overhead using VS2010. It does not result in the same code, automatic inlining enabled.
EDIT #2: I've created a unit test, eliminating all other stuff. I have no performance loss anymore, so great, there was no problem after all. Thanks for the help! And I've fixed the constructor, good call.