C++ in-class member initialization

S

Syron

Before I fell asleep last night, I had the following idea for in-class member initialization with no runtime overhead. What do you think?

#define INCLASS_INIT(ctype, name, ...) \
class _ ## name ## _INIT { \
private: ctype m_data; \
public: \
inline _ ## name ## _INIT() : \
m_data(__VA_ARGS__) {} \
inline _ ## name ## _INIT(const ctype& v) : \
m_data(v) {} \
inline operator ctype&() \
{ return m_data; } \
inline operator const ctype&() const \
{ return m_data; } \
inline ctype* operator&() \
{ return &m_data; } \
inline const ctype* operator&() const \
{ return &m_data; } \
inline ctype& operator=(const ctype& v) \
{ return m_data=v; } \
} name

// Usage:
class Foo {
public:
INCLASS_INIT(int, m_v1, 1);
INCLASS_INIT(int, m_v2, 2);
Foo() : m_v2(3)
{}
};
 
V

Victor Bazarov

Before I fell asleep last night, I had the following idea for in-class member initialization with no runtime overhead. What do you think?

#define INCLASS_INIT(ctype, name, ...) \
class _ ## name ## _INIT { \
private: ctype m_data; \
public: \
inline _ ## name ## _INIT() : \
m_data(__VA_ARGS__) {} \
inline _ ## name ## _INIT(const ctype& v) : \
m_data(v) {} \
inline operator ctype&() \
{ return m_data; } \
inline operator const ctype&() const \
{ return m_data; } \
inline ctype* operator&() \
{ return&m_data; } \
inline const ctype* operator&() const \
{ return&m_data; } \
inline ctype& operator=(const ctype& v) \
{ return m_data=v; } \
} name

// Usage:
class Foo {
public:
INCLASS_INIT(int, m_v1, 1);
INCLASS_INIT(int, m_v2, 2);
Foo() : m_v2(3)

This is confusing. What's the value of m_v2? I see it initialized to
'3' here, but is that what I'd see when I try using it elsewhere?

Curious (like a two-headed calf), but what's the point? Also, is it
intentionally limited to simple types? For instance, you can't declare
a reference that way, can you?

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top