带有std :: function的C ++ 11模板函数,该函数取决于模板参数

带有std :: function的C ++ 11模板函数,该函数取决于模板参数

问题描述:

我试图编写一个接受 std :: function 的模板函数,该函数取决于模板参数。不幸的是,编译器无法正确地将 std :: function 的参数推导。这里是一些简单的示例代码:

I am trying to write a template function that accepts a std::function which depends on the template arguments. Unfortunately the compiler is not capable of correctly deucing the arguments to the std::function. Here some simple example code:

#include <iostream>
#include <functional>

using namespace std;

void DoSomething( unsigned ident, unsigned param )
{
    cout << "DoSomething called, ident = " << ident << ", param = "  << param << "\n";
}

template < typename Ident, typename Param >
void CallFunc( Ident ident, Param param, std::function< void ( Ident, Param ) > op )
{
    op( ident, param );
}

int main()
{
    unsigned id(1);
    unsigned param(1);

    // The following fails to compile
    // CallFunc( id, param, DoSomething );

    // this is ok 
    std::function< void ( unsigned, unsigned ) > func( DoSomething );
    CallFunc( id, param, func ); 

    return 0;
}

如果我通过以下方式调用模板:

If I call the template with the following:

CallFunc( id, param, DoSomething );

我遇到以下错误:


function-tpl.cpp:25:错误:没有匹配的函数可用于调用 CallFunc(unsigned int&amp ;, unsigned int&amp ;, void(&)(unsigned int,unsigned int ))

如果我显式创建正确类型的std :: function(或将其强制转换)问题消失了:

If I explicitly create a std::function of the correct type (or cast it) the problem goes away:

std::function< void ( unsigned, unsigned ) > func( DoSomething );
CallFunc( id, param, func );

我该如何编写代码以便不需要显式临时变量?

How would I code this so that the explicit temporary is not needed?

如果使用模板,则可以完全避免使用 std :: function ,除非出于某些原因。您要专门限制函数使用 std :: function

If you are using templates, you can avoid std::function entirely, unless for some reason you want to specifically restrict the function to take std::function:

template < typename Ident, typename Param, typename Func >
void CallFunc( Ident ident, Param param, Func op )
{
    op( ident, param );
}