0

I am currently working on a program, and I want to pass a function pointer to a map for a custom comparator. In the following minimum, verifable, example, however, this produces errors:

#include <iostream>
#include <map>

struct CustomKey{
    unsigned a;
};

bool compareCustom(const CustomKey &a, const CustomKey &b){
    return a.a < b.a;
}

typedef decltype(compareCustom) CustomComparator;

int main(){
    std::map<CustomKey, unsigned, CustomComparator> customMap(&compareCustom);
    return 0;
}

Compiling the above code with either GCC or Clang produces a plethora of uninformative template errors, entirely centered around the internal implementation of std::map. This question seems to suggest that passing a function pointer type is perfectly valid. What is the issue with my code?

Cœur
  • 37,241
  • 25
  • 195
  • 267
john01dav
  • 1,842
  • 1
  • 21
  • 40
  • `typedef decltype(&compareCustom) CustomComparator;` – Swordfish Oct 07 '18 at 03:26
  • @Swordfish Doesn't just giving a function in a place where a function pointer is needed cause the compiler to treat it is a function pointer? – john01dav Oct 07 '18 at 03:27
  • @john01dav No, function names can decay into a pointer to that function in some cases, but `decltype(functionName)` is not one of those cases. – Miles Budnek Oct 07 '18 at 03:29
  • @MilesBudnek What are those cases? – john01dav Oct 07 '18 at 03:30
  • @john01dav It's an implicit conversion. If you're initializing or assigning to a function pointer, the function name will decay into a pointer to initialize it. It's very similar to the way arrays decay into a pointer to their first element. – Miles Budnek Oct 07 '18 at 03:31

1 Answers1

3

Passing a function pointer is valid, but passing a function is not.

typedef decltype(compareCustom) CustomComparator;

actually makes CustomComparator of type bool(const CustomKey&, const CustomKey&), that's the function itself, not a pointer.

You should use:

typedef decltype(compareCustom) *CustomComparator;
llllllllll
  • 16,169
  • 4
  • 31
  • 54