tags:

views:

240

answers:

3

I'm trying to write a template which gets the type of a functionpointer as templateargument and the corresponding functionpointer as a function argument, so as a simplyfied example I'm doing this right now:

int myfunc(int a)
{ return a; }

template<typename T, typename Func> struct Test
{
    typedef typeof(myfunc) Fun;
    static T MyFunc(T val, Func f)
    {
        return f(val);
    }
};

int main(void)
{
    std::cout<<Test<int, typeof(myfunc)>::MyFunc(5, myfunc)<<std::endl;
}

However this code instantly crashes. If I change the type of f to Fun it works perfectly. So what am I doing wrong and how can I get this to work?

I'm using mingw under windows vista if that behaviour in case that behaviour is compiler dependent.

A: 

That code works just fine for me!

Autopulated
+2  A: 

typeof isn't valid C++, but if I replace your two lines involving them with these, then your code works fine with either Fun or Func in the definition of MyFunc.

typedef int (*Fun)(int);

and

std::cout<<Test<int, int(*)(int)>::MyFunc(5, myfunc)<<std::endl;
Charles Bailey
I was also doubting the `typeof` function...
xtofl
+2  A: 

You don't really need the Test class for this scenario, and Why use the typeof function here?

template< typename T, typename fT > 
T TestMyFunc( T t, fT f ) {
   return f(t);
};

will do, and no fiddling with function pointer types:

std::cout << TestMyFunc(5,myfunc) << std::endl;

The template arguments are deduced automatically for functions!

xtofl