【发布时间】:2013-03-10 16:01:51
【问题描述】:
在模板化成员函数中使用 std::function 时出现编译错误,以下代码是一个简单示例:
#include <functional>
#include <memory>
using std::function;
using std::bind;
using std::shared_ptr;
class Test {
public:
template <typename T>
void setCallback(function<void (T, int)> cb);
};
template <typename T>
void Test::setCallback(function<void (T, int)> cb)
{
// do nothing
}
class TestA {
public:
void testa(int a, int b) { }
};
int main()
{
TestA testA;
Test test;
test.setCallback(bind(&TestA::testa, &testA, std::placeholders::_1, std::placeholders::_2));
return 0;
}
并出现以下编译错误:
testtemplate.cpp:在函数'int main()'中:
testtemplate.cpp:29:92: 错误:没有匹配的函数调用 'Test::setCallback(std::_Bind_helper)(int, int), TestA, 常量 std::_Placeholder&, 常量 std::_Placeholder&>::type)'
testtemplate.cpp:29:92: 注意:候选人是:testtemplate.cpp:10:7: 注意:模板 void Test::setCallback(std::function)
testtemplate.cpp:10:7: 注意:模板参数 扣减/代换失败:
testtemplate.cpp:29:92: 注意:'std::_Bind(TestA*, std::_Placeholder, std::_Placeholder)>' 不是从'std::function' 派生的
我使用的是 C++11 和 g++ 4.7
【问题讨论】:
-
说
test.setCallback<int>(bind...)。bind的结果不是std::function,所以没有参数推导。 -
请告诉我你认为编译器是如何推断出
T的。 -
@Xeo 我是模板的大一新生,不知道dedece T 是如何工作的。一些材料有帮助吗?
-
@user1679133:一般情况下,当
std::function是参数时,除非您传递std::function,否则您必须完整地拼出类型。 -
Lambdas 是比
std::bind更好的选择
标签: c++ function templates bind