4

I am getting an "unresolved overloaded function type" error when trying to pass an overloaded static function to an std::function.

I am aware of similar questions, such as this and this. However, even though the answers there work for getting the address of the right function into a function pointer, they fail with std::function. Here is my MWE:

#include <string>
#include <iostream>
#include <functional>

struct ClassA {
  static std::string DoCompress(const std::string& s) { return s; }
  static std::string DoCompress(const char* c, size_t s) { return std::string(c, s); }
};

void hello(std::function<std::string(const char*, size_t)> f) {
  std::string h = "hello";
  std::cout << f(h.data(), h.size()) << std::endl;
}

int main(int argc, char* argv[]) {
  std::string (*fff) (const char*, size_t) = &ClassA::DoCompress;
  hello(fff);
  hello(static_cast<std::string(const char*, size_t)>(&ClassA::DoCompress));
}

Could someone explain why the static_cast doesn't work when the implicit one does?

Community
  • 1
  • 1
David Nemeskey
  • 640
  • 1
  • 5
  • 16
  • _"... when the implicit one does?"_ That it compiles without error, is because it will cast regardless of the involved types. It's just like applying `reinterpret_cast<>`. – πάντα ῥεῖ Oct 28 '15 at 10:55
  • @πάντα ῥεῖ True, but in my case, not even `reinterpret_cast` worked. Knowing what my mistake was, of course, makes it obvious why. :) – David Nemeskey Oct 28 '15 at 11:53

1 Answers1

6

You can't cast to a function type. You probably meant to cast to a pointer type:

hello(static_cast<std::string(*)(const char*, size_t)>(&ClassA::DoCompress));
//                           ^^^
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
  • I see, so the right answers is "because I am stupid". :) Just a short follow-up question then: what are function types good for then? Only to be used as template parameters to e.g. `std::function`? – David Nemeskey Oct 28 '15 at 11:06
  • 2
    @DavidNemeskey And for creating pointers and references to them. E.g. `using FuncType = double (int, char); FuncType *f = &myFunc;` – Angew is no longer proud of SO Oct 28 '15 at 11:26
  • @DavidNemeskey a function type is valid in [some contexts](http://coliru.stacked-crooked.com/a/91b7611f93fc0c3f) unrelated to meta-programming – Piotr Skotnicki Oct 28 '15 at 11:33