I
Immortal Nephi
Why do I get compiler error message? It explains that I am not
allowed to create variable in the template parameter, but constant
variable is acceptable.
How can I fix the error?
c:\test_mycode.cpp(24) : error C2975: 'size' : invalid template
argument for 'Test', expected compile-time constant expression
c:\test_template.h(41) : see declaration of 'size'
// Test_Template.h
#if !defined( TEST_TEMPLATE_H )
#define TEST_TEMPLATE_H
enum Type {
Sample_Type1,
Sample_Type2
};
template< Type >
struct Traits {
};
template<>
struct Traits< Sample_Type1 > {
static const int x;
static const int y;
};
template<>
struct Traits< Sample_Type2 > {
static const int x;
static const int y;
};
template< typename T, int size >
class Test {
};
#endif // end macro !defined( TEST_TEMPLATE_H )
// Test_Template.cpp
#include "Test_Template.h"
const int Traits< Sample_Type1 >::x = 1;
const int Traits< Sample_Type1 >::y = 2;
const int Traits< Sample_Type2 >::x = 10;
const int Traits< Sample_Type2 >::y = 20;
template
class Test< int, Traits< Sample_Type1 >::x >;
template
class Test< int, Traits< Sample_Type2 >::x >;
// main.cpp
#include "Test_Template.h"
const Type type = Sample_Type1;
const int size = Traits< type >::x;
int main() {
// Test< int, size > test;
Test< int, Traits< type >::x > test2;
return 0;
}
allowed to create variable in the template parameter, but constant
variable is acceptable.
How can I fix the error?
c:\test_mycode.cpp(24) : error C2975: 'size' : invalid template
argument for 'Test', expected compile-time constant expression
c:\test_template.h(41) : see declaration of 'size'
// Test_Template.h
#if !defined( TEST_TEMPLATE_H )
#define TEST_TEMPLATE_H
enum Type {
Sample_Type1,
Sample_Type2
};
template< Type >
struct Traits {
};
template<>
struct Traits< Sample_Type1 > {
static const int x;
static const int y;
};
template<>
struct Traits< Sample_Type2 > {
static const int x;
static const int y;
};
template< typename T, int size >
class Test {
};
#endif // end macro !defined( TEST_TEMPLATE_H )
// Test_Template.cpp
#include "Test_Template.h"
const int Traits< Sample_Type1 >::x = 1;
const int Traits< Sample_Type1 >::y = 2;
const int Traits< Sample_Type2 >::x = 10;
const int Traits< Sample_Type2 >::y = 20;
template
class Test< int, Traits< Sample_Type1 >::x >;
template
class Test< int, Traits< Sample_Type2 >::x >;
// main.cpp
#include "Test_Template.h"
const Type type = Sample_Type1;
const int size = Traits< type >::x;
int main() {
// Test< int, size > test;
Test< int, Traits< type >::x > test2;
return 0;
}