3.05.2011

C++ template function callbacks

I'm having problems implementing a flexible memoization class in C++. The point is you can't make it clean without RTTI support if you want to specify a function somewhere in another class. I tried making a special memoization entry class that holds the necessary type information, but this does somehow NOT work as I'm trying to do something T::Type if T is a template parameter. I haven't seen a solution to this problem and want to keep it "as inline as possible" this time. But thinking about how rarely I'd actually the calculation function itself, I may consider using a callback in that case. At first I searched the internet if it's actually possible to do so, but found nothing of use. So I just tried it out and it works by implicitely AND explicitly instanciating a template function when assigning it's addresse to a function pointer:

#include

template
void func(T i) {printf("%d\n",i);}

typedef void (*templatefunc)(float);

int main() {
templatefunc tf=func/*
*/;
tf(-2);
return 0;
}


You see, GCC outputs a warning about i beeing a float, which means template instanciation was successful! I don't know whether it's standard, but I bet so. It works in all cases and it's ok as "fallback solution" cause the my template ideas never work due to C++' fucky template system. I need to push my own language own day.

No comments: