F
Frederick Gotham
I don't like macros for a few reasons -- here's just a few...
Reason 1:
namespace ArbitraryNamespace {
#define Func(i) ( i + '0' )
}
int Func( int const b );
Reason 2:
#define Square(a) (a*a)
int main()
{
int i = 7;
Square(i++);
}
Therefore, wherever possible, I use an alternative (e.g. templates,
typedef's, enum's, global const variables).
The following code doesn't compile because a function call can never
evaluate to a compile time constant:
unsigned TwoPowerX( unsigned const x )
{
return 1U << x;
}
int main()
{
int array[ TwoPowerX(5) ];
}
I believe it was Alf P. Steinbach who devised a suitable alternative:
template<unsigned x>
struct TwoPowerX {
static unsigned const val = 1U << x;
};
int main()
{
int array[ TwoPowerX<5>::val ];
}
Yes, this does the trick, but in my view, it isn't quite optimal because
we don't have our domestic function-call syntax.
Has anyone got any ideas as to how we could achieve this whilst retaining
our function-call syntax? (Without using a macro of course!)
As a side note, depending on the outcome of this thread, I may make a
suggestion to comp.std.c++ to add the following functionality to the
language, which might make use of the "switch" keyword:
switch TwoPowerX( unsigned const x ) return 1U << x;
int main()
{
int array[ TwoPowerX(5) ];
}
The "switch" keyword before the function definition would indicate that
it can evaluate to a compile-time constant.
Reason 1:
namespace ArbitraryNamespace {
#define Func(i) ( i + '0' )
}
int Func( int const b );
Reason 2:
#define Square(a) (a*a)
int main()
{
int i = 7;
Square(i++);
}
Therefore, wherever possible, I use an alternative (e.g. templates,
typedef's, enum's, global const variables).
The following code doesn't compile because a function call can never
evaluate to a compile time constant:
unsigned TwoPowerX( unsigned const x )
{
return 1U << x;
}
int main()
{
int array[ TwoPowerX(5) ];
}
I believe it was Alf P. Steinbach who devised a suitable alternative:
template<unsigned x>
struct TwoPowerX {
static unsigned const val = 1U << x;
};
int main()
{
int array[ TwoPowerX<5>::val ];
}
Yes, this does the trick, but in my view, it isn't quite optimal because
we don't have our domestic function-call syntax.
Has anyone got any ideas as to how we could achieve this whilst retaining
our function-call syntax? (Without using a macro of course!)
As a side note, depending on the outcome of this thread, I may make a
suggestion to comp.std.c++ to add the following functionality to the
language, which might make use of the "switch" keyword:
switch TwoPowerX( unsigned const x ) return 1U << x;
int main()
{
int array[ TwoPowerX(5) ];
}
The "switch" keyword before the function definition would indicate that
it can evaluate to a compile-time constant.