samedi 13 mars 2021

std::function and std::bind: how to load a std::bind with a function template

I use a function template to load a std::bind obj, my code:

#include <iostream>
#include <functional>

template<typename RT_, typename ...Args>
void installCallback(const char name[], const std::function<RT_(Args...)> &func)
{

}

int add(int a, int b)
{
    return a + b;
}

int main(int argc, char *argv[])
{

    installCallback("add01", std::bind(add, std::placeholders::_1, std::placeholders::_2));
    installCallback<int, int, int>("add01", std::bind(add, std::placeholders::_1, std::placeholders::_2));// didn't work either

    // this work well
    std::function<int(int, int)> fun = std::bind(add, std::placeholders::_1, std::placeholders::_2);
    installCallback("add02", fun);
    return 0;
}

, I got this error:

/home/tong/Documents/awesome_auto_drive/awe_auto/sample/module/main.cpp:20:90: error: no matching function for call to ‘installCallback(const char [6], std::_Bind_helper<false, int (&)(int, int), const std::_Placeholder<1>&, const std::_Placeholder<2>&>::type)’ 20 | installCallback("add01", std::bind(add, std::placeholders::_1, std::placeholders::2)); | ^ $./main.cpp:6:6: note: candidate: ‘template<class RT, class ... Args> void installCallback(const char*, std::function<_Res(ArgTypes ...)>&&)’ 6 | void installCallback(const char name[], std::function<RT(Args...)> &&func) | ^~~~~~~~~~~~~~~ $./main.cpp:6:6: note: template argument deduction/substitution failed: $./main.cpp:20:90: note: ‘std::_Bind_helper<false, int (&)(int, int), const std::_Placeholder<1>&, const std::_Placeholder<2>&>::type’ {aka ‘std::_Bind<int (*(std::_Placeholder<1>, std::_Placeholder<2>))(int, int)>’} is not derived from ‘std::function<_Res(_ArgTypes ...)>’ 20 | installCallback("add01", std::bind(add, std::placeholders::_1, std::placeholders::_2)); | ^ sample/module/CMakeFiles/module.dir/build.make:62: recipe for target 'sample/module/CMakeFiles/module.dir/main.cpp.o' failed make[2]: *** [sample/module/CMakeFiles/module.dir/main.cpp.o] Error 1 CMakeFiles/Makefile2:2665: recipe for target 'sample/module/CMakeFiles/module.dir/all' failed make[1]: *** [sample/module/CMakeFiles/module.dir/all] Error 2 Makefile:129: recipe for target 'all' failed make: *** [all] Error 2

who can tell me, what happened?

Aucun commentaire:

Enregistrer un commentaire