I'm new to metaprogramming, and I am having a const-related issue when using a tab with it.
Let's say we have several "types". Each of the types have different version, and we shall be able to handle all vesrion for each type. For that, we use a struct that contains standard info about the type, and an array containing info for each version.
The thing is, each type does not have the same number of versions. Also, the versions numbers are not very high, so I prefer not to use dynamic allocation of the said tables. But if I do static allocation, I need to have a table with the same size for each instance of the structure. That means, I have to get the highest version value and use it as the size of the array.
Here I come : I want to create a small metaprogramming template which gives the highest version value @ compile time, so I can have a fixed size of the array that will surely contains the necerrasy info for each type. But I get a compile error.
Here is a simplified sample code that reproduce the issue (the error follows it)
#include <stdio.h>
// change values here
#define VERSION_ALPHA 3
#define VERSION_BETA 5
#define VERSION_GAMMA 2
// different available types
enum TYPES
{
T_ALPHA = 0,
T_BETA,
T_GAMMA,
T_COUNT, // number of types
};
// to access versions more easily from code
static const int typeVersions[T_COUNT] =
{
VERSION_ALPHA,
VERSION_BETA,
VERSION_GAMMA
};
// this meta is used to get the highest version values between all types
template<int i>
class HighestVersion
{
private:
// version of type -1
enum
{
PREVIOUS = HighestVersion<i-1>::VALUE
};
public:
// current max value
enum
{
VALUE = (typeVersions[i] > PREVIOUS ? typeVersions[i] : PREVIOUS)
};
};
// first version
template<>
class HighestVersion<0>
{
public:
// current max value
enum
{
VALUE = typeVersions[0]
};
};
// highest version macro
#define HIGHEST_VERSION HighestVersion<T_COUNT>::VALUE
// holds info about a single type
struct TypeInfo
{
char * s_pName; // name of the type as string
unsigned int s_Flags[HIGHEST_VERSION]; // flags for each available version of this type
};
int main()
{
// instanciate
TypeInfo infos[T_COUNT];
// do stuff, set name, load flags....
/*...*/
// for test purpose, print max version value (should print 5 in this situation)
printf("%d\n", HIGHEST_VERSION);
}
The compiler says :
error C2057: expected constant expression
@ the lines
VALUE = (typeVersions[i] > PREVIOUS ? typeVersions[i] : PREVIOUS)
and
VALUE = typeVersions[0]
It seems that the compiler tells me that the table's contents are not constant. I assume it's because the table is interpreted as a pointer which is no constant in that case (so if the pointer changes the contents are not the same). Is there a way to correct that so I can use the script ? It will make the user to not need to manually set the size of that table...
Thanks in advance :)