Search code examples
c++function-pointers

Function pointer declaration misreads argument type


I have problems using a struct as an argument in the declaration of a function pointer (MyFunction) below:

#include <iostream>

struct Record {
    int x, y;
};

// MyFunction returns a changed version of Record
typedef Record (*MyFunction)(const &Record, int);

// Increment record by change
Record add(const Record &rec, int change) {
    return Record{rec.x + change, rec.y + change};
}

// Apply a change to Record by function f
Record apply(MyFunction f, const Record &rec, int change) {
    return f(rec, change);
}

int main(int argc, char *argv[])
{
    Record 
      myRec = {3,5},
      result = apply(add, myRec, 10); // compilation error here
    std::cout << result.x << " " << result.y << std::endl;
}

gcc (6.4.2) gives a compilation error in line 25 (marked above): invalid conversion from 'Record (*)(const Record&, int)' to 'MyFunction' {aka 'Record (*)(const int&, int)'}

What? How come the declaration of MyFunction has turned the const Record& type into const int&?


Solution

  • You're trying to define a reference argument named Record without a type. It should be spelled like this if you meant a reference to Record:

    typedef Record (*MyFunction)(const Record&, int);
    

    Or rather:

    using MyFunction = Record (*)(const Record&, int);