2

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.

4
  • 1
    typeof is not part of C++, so that doesn't even compile on my compiler Commented Dec 19, 2009 at 20:42
  • Compiles and runs perfectly here. Commented Dec 19, 2009 at 20:44
  • typeof is a GCC extension. I assume it's not available on MSVC. Commented Dec 19, 2009 at 20:54
  • decltype isn't in the current version of C++, but is due in the next version. gcc generats the expected errors so long as it is in C++ mode (e.g. -std=c++98). Commented Dec 19, 2009 at 21:45

2 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

Comments

2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.