avoiding #define

Hi,

Here are my requirements:

- a Currency object can only contain double m_value as a member (I need sizeof(Currency) to be the smallest size possible).
- certain Currency types have characteristics like "pennySize", etc...

To satisfy these requirements, I can do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Currency
{
public:
  virtual double round( void ) const = 0;
  void setValue( double v ) { m_value = v; }
protected:
  Currency( double v ) : m_value( v ) { }
private:
  double m_value;
};

#define CURRENCY_TYPE( NAME, PENNYSIZE ) \
class NAME : public Currency \
{ \
public: \
  virtual double round( void ) const { return RoundTo( m_value, PENNYSIZE ); } \
  ... \
};

CURRENCY_TYPE( JPY, 1.0  )
CURRENCY_TYPE( USD, 0.01 )
\\ and many, many more...


RoundTo() is defined elsewhere.

Is there any way I can avoid using #define in this case, while satisfying my requirements? It would be best if there is a dynamic/run-time construct, but a static/compile-time construct would also suffice.

I thought about using templates, but I can't pass in constants like this, right?

Thanks in advance.

Last edited on
You can use a template:
1
2
3
4
5
6
template < unsigned PENNYSIZE > // notice: it is integral
class Currency
{
    // all other stuff...
    double round( ) const { return RoundTo( m_value, PENNYSIZE/100. );  } // notice: PENNYSIZE divided by 100 the dot makes it a double
};
Last edited on
Thanks Bazzy!

I will try it out...
Topic archived. No new replies allowed.