std :: function中带有静态函数的"未解析的重载函数类型"

Dav*_*key 4 c++ function-pointers c++11 std-function

尝试将重载的静态函数传递给时,我收到"未解析的重载函数类型"错误std::function.

我知道类似的问题,比如这个这个.但是,即使那里的答案用于将正确函数的地址转换为函数指针,它们也会失败std::function.这是我的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));
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么static_cast隐含的那个不起作用?

Pio*_*cki 6

您无法转换为函数类型.你可能想要转换为指针类型:

hello(static_cast<std::string(*)(const char*, size_t)>(&ClassA::DoCompress));
//                           ^^^
Run Code Online (Sandbox Code Playgroud)

  • @DavidNemeskey用于创建指针和引用它们.例如`使用FuncType = double(int,char); FuncType*f =&myFunc;` (2认同)