使用std :: function和std :: bind时,模板参数推导/替换失败

hai*_*g31 22 c++ templates bind function

在模板化成员函数中使用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;
}
Run Code Online (Sandbox Code Playgroud)

并带来以下编译错误:

testtemplate.cpp:在函数'int main()'中:

testtemplate.cpp:29:92:错误:没有匹配的函数调用"测试:: setCallback(STD :: _ Bind_helper)(INT,INT),种皮,常量性病:: _占位符<1>&,常量性病:: _占位符<2>&> ::类型)"

testtemplate.cpp:29:92:注意:候选者是:testtemplate.cpp:10:7:注意:模板void test :: setCallback(std :: function)

testtemplate.cpp:10:7:注意:模板参数扣除/替换失败:

testtemplate.cpp:29:92:注: '的std :: _绑定(外种皮*,性病:: _占位符<1>,的std :: _占位符<2>)>' 不是从 '的std ::函数' 衍生

我正在使用C++ 11和g ++ 4.7

mas*_*oud 11

要找出问题,请单独声明:

auto f = bind(&TestA::testa, &testA, _1, _2); // OK
test.setCallback(f);                          // <<--- Error is here
Run Code Online (Sandbox Code Playgroud)

setCallback需要知道T它的类型,它不能从中推断出来f,所以给它一个类型

test.setCallback<TYPE>(f); // TYPE: int, float, a class, ...
Run Code Online (Sandbox Code Playgroud)

  • @ user1679133:每天编程和练习,这是学习编程概念的唯一方法.我们都这样做的方式.并阅读Stackoverflow的问答. (2认同)