当使用std :: function和std :: bind时,模板参数推导/替换失败 [英] template argument deduction/substitution failed, when using std::function and std::bind
问题描述
在模板化成员函数中使用std :: function时出现编译错误,下面的代码就是一个简单的例子:
#include< functional>
#include< memory>
使用std :: function;
使用std :: bind;
使用std :: shared_ptr;
class Test {
public:
template< typename T>
void setCallback(function< void(T,int)> cb);
};
模板< 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.setCallback(bind(& TestA :: testa,& testA,std :: placeholders :: _ 1,std :: placeholders :: _ 2));
返回0;
}
然后出现以下编译错误:
testtemplate.cpp:在函数'int main()'中:
$ b testtemplate.cpp:29:92:错误:调用
时没有匹配函数Test :: setCallback(std :: _ Bind_helper)(int,int),
TestA,const std :: _占位符< 1&;,const
:std :: _占位符< 2&>类型)'
testtemplate.cpp:29:92:note:candidate is:testtemplate.cpp:10: 7:
note:template void Test :: setCallback(std :: function)
testtemplate.cpp:10:7:note:template argument
的扣除/替换失败:
testtemplate.cpp:29:92:note:'std :: _ Bind(TestA *,std :: _ Placeholder< 1>,
std :: _ Placeholder< 2>)>'不是从'std :: function'派生的
++ 11和g ++ 4.7
为了弄清问题,让单独的语句:
auto f = bind(&TestA :: testa,& testA,_1,_2); // OK
test.setCallback(f); //<<<< ---错误在这里
setCallback
需要知道 T
的类型,并且它不能从 f
推论它,所以给它类型
test.setCallback< TYPE>(f); // TYPE:int,float,a class,...
I have a compile error when using std::function in a templated member function, the following code is a simple example:
#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;
}
And come with the following compile error:
testtemplate.cpp: In function ‘int main()’:
testtemplate.cpp:29:92: error: no matching function for call to ‘Test::setCallback(std::_Bind_helper)(int, int), TestA, const std::_Placeholder<1>&, const std::_Placeholder<2>&>::type)’
testtemplate.cpp:29:92: note: candidate is: testtemplate.cpp:10:7: note: template void Test::setCallback(std::function)
testtemplate.cpp:10:7: note: template argument deduction/substitution failed:
testtemplate.cpp:29:92: note: ‘std::_Bind(TestA*, std::_Placeholder<1>, std::_Placeholder<2>)>’ is not derived from ‘std::function’
I'm using C++11 and g++ 4.7
To figure out the problem let separate statements:
auto f = bind(&TestA::testa, &testA, _1, _2); // OK
test.setCallback(f); // <<--- Error is here
setCallback
needs to know type of T
and it can't deduce it from f
, so give it a type
test.setCallback<TYPE>(f); // TYPE: int, float, a class, ...
这篇关于当使用std :: function和std :: bind时,模板参数推导/替换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!