Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading type cast operator, to cast to a pointer to function [duplicate]

I'm having some difficulty, overloading the cast to pointer to function operator of a class. In code, what I want is this:

typedef int(*funcptrtype)(int);

struct castable {
   operator funcptrtype() {return NULL;}
};

but I want to be able to do it without using the typedef. If you're curious, I need this, because pre-c++11 template aliases aren't available (so the typedef trick is not an option in templated contexts...)

I would normally expect this to work:

operator int(*)(int)() {return NULL;}

But it doesn't. The compiler (g++ 4.6.1) says:

error: ‘<invalid operator>’ declared as function returning a function

This works:

int (* operator()())(int){return 0;}

But you're actually overloading the operator() to return a function pointer :)

The standard says:

The conversion-type-id shall not represent a function type nor an array type

But it doesn't say function pointer type (The first code snipplet works anyway...).

Does anyone know the right syntax w/o typedef?

like image 278
enobayram Avatar asked Mar 08 '26 11:03

enobayram


1 Answers

The grammar doesn't allow this: the type in a conversion operator declaration is a type-specifier, not a type-id. You have to use a typedef or alias; in a template context, use the usual replacement:

template<typename T>
struct something {
  typedef T (*type)(int);
};
like image 142
Philipp Avatar answered Mar 10 '26 03:03

Philipp