Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should this C++ syntax be read? [closed]

Tags:

c++

syntax

I'm probably being a complete idiot, but I've just seen this C++ syntax and I can't for the life of me work out what it's doing:

(*x)(&a, b, c);

A quick answer would be greatly appreciated.

like image 424
Ed King Avatar asked Jan 15 '13 15:01

Ed King


1 Answers

Well there can be many more possibilities: it all depends on the type of all entities: x, a, b, c. In C++, you can overload even comma operator.

But I will only focus on x, and see how things turn out to be. The actual answer, however, will be too long if all combinations are taken into account.

(*x)(&a, b, c);

Here x could one of these:

  • A function pointer
  • A pointer to function object.
  • An iterator which on dereferencing returns function pointer or function object.
  • (one more at the bottom which is partially covered by the previous one!)

And then you're invoking it passing three arguments to it.

Here are few examples, assuming all other entities (a, b c) as int:

  • An assumption

     int a,b,c; //FIXED as per the assumption
    
  • Function pointer

     void f(int *,int, int);
     auto *x = f;
     (*x)(&a,b,c); //x is function pointer 
     x(&a,b,c);    //works fine, even without (*x)
    
  • Function object

    struct X { void operator()(int*,int,int); };
    
    X y, *x = &y;
    (*x)(&a,b,c);  //x is pointer to function object
    
  • Iterator

    std::list<std::function<void(int*,int,int)> l {X(), f};
    auto x = l.begin();  //x is an iterator
    (*x)(&a,b,c);  //(*x) is function object
    ++x;
    (*x)(&a,b,c);  //(*x) is function object (still!)
    
    //OR
    std::list<void(int*,int,int)> l {f};
    auto x = l.begin();  //x is an iterator
    (*x)(&a,b,c);  //(*x) is function pointer!
    

As @David said in comment that:

However, there is a fourth possibility: x could be an instance of some class that overloads operator* to return a function pointer or function object.

which is true, but I believe this possibility is partially covered by iterator, or at least the iterator example gave you enough hint to figure it out yourself. :-)

Hope that helps.

like image 80
Nawaz Avatar answered Nov 15 '22 08:11

Nawaz