带有std :: function的C ++ 11模板函数,该函数取决于模板参数 [英] C++11 Template function that takes a std::function which depends of template parameters

查看:99
本文介绍了带有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& ;, unsigned int& ;, 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 );
}

这篇关于带有std :: function的C ++ 11模板函数,该函数取决于模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆