"Amit" <am***********@intel.com> schrieb im Newsbeitrag
news:d7**********@news01.intel.com...
Greetings.
How does one associate a integer variable to a non-type template parameter
?
Is there anyway of doing it in an easy way using partial specialization ?
so
what I have is something to the effect of,
You could use a function table or a switch statement:
template<typename T, int N>
class X
{
public:
bool operator()(T* p){
// do something;
return false;
}
};
template<typename T>
class X<T, 0>
{
public:
bool operator()(T* p){
return true;
}
};
template<typename T>
class X<T, 1>
{
public:
bool operator()(T* p){
return true;
};
};
template<int N, class T> bool xFunction(T* p)
{
return X<T,N>()(p);
}
template<class T> struct XFunctionTable
{
typedef bool(*Function)(T*);
enum {NumSpecializations = 5};
static bool validIndex(int);
static Function functions[NumSpecializations];
};
template<class T> bool XFunctionTable<T>::validIndex(int i)
{
return i >= 0 && i < NumSpecializations;
}
template<class T> typename XFunctionTable<T>::Function
XFunctionTable<T>::functions[NumSpecializations]
={&xFunction<0>,&xFunction<1>, &xFunction<2>, &xFunction<3>, &xFunction<4>};
template<typename T> struct MyClass
{
void foo1();
void foo2();
};
template<typename T> void
MyClass<T>::foo1()
{
int val;
val = 2; // evaluate val somehow
if(XFunctionTable<T>::validIndex(val))
{
T* someptr_p = 0;
XFunctionTable<T>::functions[val]( someptr_p);
}
else
;// some appropriate error handling.
}
template<typename T> void
MyClass<T>::foo2()
{
int val;
val = 1; // evaluate val somehow
T* someptr_p = 0;
switch(val)
{
case 0:
X<T, 0>()(someptr_p);
break;
case 1:
X<T, 1>()(someptr_p);
break;
case 2:
X<T, 2>()(someptr_p);
break;
case 3:
X<T, 3>()(someptr_p);
break;
case 4:
X<T, 4>()(someptr_p);
break;
default:
;// some appropriate error handling.
}
}
int main(int argc, char* argv[])
{
MyClass<int> test;
test.foo1();
test.foo2();
return 0;
}
Regards,
Arne