Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A typedef that refers to itself

Tags:

c++

typedef bool (*Foo)(Foo a, Foo b);

How do you declare a function pointer that accepts itself in its parameters?

like image 979
Tergiver Avatar asked Dec 21 '11 22:12

Tergiver


People also ask

What is a typedef function?

typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.

Can a struct contain itself?

Pointers to structures Although a structure cannot contain an instance of its own type, it can can contain a pointer to another structure of its own type, or even to itself.

What is typedef void?

typedef void (*MCB)(void); This is one of the areas where there is a significant difference between C, which does not - yet - require all functions to be prototyped before being defined or used, and C++, which does.

What does it mean to typedef a struct?

The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.


1 Answers

Indirectly:

struct Foo{
  typedef bool (*FooPtr)(Foo a, Foo b);
  Foo(FooPtr p)
      : p(p)
  {}

  bool operator()(Foo a, Foo b) const{
    return p(a,b);
  }

  FooPtr p;
};

struct Bar{
    Bar(Foo f)
        : some_callback(f)
    {}

    Foo some_callback;
};

bool a_callback(Foo a, Foo b){
    return false;
}

int main() {
    Bar b(a_callback);
    b.some_callback(Foo(a_callback), Foo(a_callback));
}

Not that I could ever see any use in that, as you can see from my example.

like image 191
Xeo Avatar answered Oct 14 '22 20:10

Xeo