在 std::function 中使用静态函数的"unresolved overloaded function type"

"unresolved overloaded function type" with static function in std::function

本文关键字:function type unresolved overloaded std 静态函数      更新时间:2023-10-16

在尝试将重载静态函数传递给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));
}

有人能解释一下为什么static_cast不起作用,而隐式的却起作用吗?

不能强制转换为函数类型。您可能想强制转换为指针类型:

hello(static_cast<std::string(*)(const char*, size_t)>(&ClassA::DoCompress));
//                           ^^^
相关文章: