tags:

views:

81

answers:

6

I am a newb and I am trying to better myself at good practice and design so consider this before reading the following.

I am creating a singleton class, and I have quite a few static members. Instead of calling the members every time like this...

THECLASS::member

I was thinking about using a define macro to make it shorter.

#define(THECLASS::member, shortMember);

So my question is, will that hurt for cross platforms or cross compilers.

+1  A: 

If your class is made up of all static methods, you could instead declare a namespace with the methods, then when you want to use the methods in a .cpp file, include at the top of the file:

using namespace [your-namespace];

Just don't do this in a header file, or you will pollute the namespace of all other files that include this header.

Justin Ardini
+7  A: 
Mewp
+1 for readability being more important. You only type a piece of code once (figuratively) but it gets read many times, and not just by you.
ChrisF
you have shortMember and THECLASS::member swapped. EDIT: I see you have fixed it.
Niki Yoshiuchi
I think that was a great point.
numerical25
+1  A: 

Most likely, but you open yourself up the namespace conflicts that having classes was supposed to avoid in the first place, so its probably not a good idea.

Nathan Reed
+6  A: 

You would need to use the correct syntax for a macro definition:

#define shortMember THECLASS::member

However, don't do this.

  • All macros are in a single namespace and the replacement takes place everywhere, so you end up with a huge maintenance headache.

  • This hurts the readability and comprehensibility of the code because it makes it much more difficult where names come from and to what they refer

The good practice in this case is to spell out the name wherever you use it.

James McNellis
A: 

A define will work, but not the define you wrote in your question. Something along the lines of:

class SingletonImpl {
...
SingletonImpl *getInstance() { return m_instance; }
}

#define SINGIMPL SingletonImpl::getInstance()

which can then be used like this:

SINGIMPL->whatever();

However keep in mind that macros just do text replacement and therefore ignore things like namespaces.

Niki Yoshiuchi
A: 

To answer the question in your title, yes a properly written DEFINE will work on all platforms. However as others have said it is not a good idea for your purpose, for the reasons cited.

Steve Fallows