【发布时间】:2016-11-14 19:30:48
【问题描述】:
所以我有一些具有两个函数的泛型类,它们将函数作为参数。一个接受函数指针,一个接受 std::function。两者都有一个模板参数。
#include <functional>
#include <memory>
namespace {
void example(const std::shared_ptr<const int>&) {}
}
class Generic {
public:
Generic() {}
virtual ~Generic() {}
template <typename Targ>
void doWork(std::function<void(const std::shared_ptr<const Targ>&)> arg) {}
template <typename Targ>
void doWork2(void(*function)(const std::shared_ptr<const Targ>&)) {}
};
class Special : public Generic {
public:
Special() {
//doWork(&example); // Fail!
doWork<int>(&example); // OK!
std::function<void(const std::shared_ptr<const int>&)> func = &example;
doWork(func); // OK!
doWork2(&example); // OK!
}
};
int main(int argc, char** argv) {
Special special;
return 0;
}
使用函数指针它编译,但使用 std::function 它不编译。为什么这里的模板推演失败了?
Clang 报告:
example.cpp:27:9: error: no matching member function for call to 'doWork'
doWork(&example);
^~~~~~
example.cpp:14:10: note: candidate template ignored: could not match 'function<void (const shared_ptr<const type-parameter-0-0> &)>' against 'void (*)(const std::shared_ptr<const int> &)'
void doWork(std::function<void(const std::shared_ptr<const Targ>&)> arg) {
^
1 error generated.
【问题讨论】:
-
example不是std::function,并且可能会从这个函数构造几个std::function。 -
@Jarod42 但
&example是函数指针,我可以将函数指针作为std::function传递,不是吗?