为什么我的C ++编译器不能推导boost函数的模板参数? [英] Why can't my C++ compiler deduce template argument for boost function?

查看:172
本文介绍了为什么我的C ++编译器不能推导boost函数的模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个这样的方法:

  template< class ArgT& 
void foo(ArgT arg,:: boost :: function< void(ArgT)> func)
{
func(arg)
}

并使用它,例如 - :

  foo(2,[](int i) - > void {cout<< i<< endl;}); 

为什么编译器不能推导类型,因为它绝对是一个 int



我得到'void foo(ArgT,boost :: function< void(ArgT)>)'无法从anonymous-namespace::< lambda0>'中推导出boost :: function< void(ArgT)>的模板参数。

std :: function<> (或 boost :: function< ;> )实例,因为函数 operator()参数类型不能自动推断。



稍微不同的是,lambda表达式的自然类型是一个带有无参数构造函数的函子,以及带有签名 operator() void operator()(int)const 。显然这个事实可能是你和我,不能自动推断 ArgT 应该解析为 int ,因为lambdas是函数和函数 operator()可以重载和模板。



TL; DR:是不可能的。


I define a method like so:

template <class ArgT>
void foo(ArgT arg, ::boost::function< void(ArgT) > func)
{
    func(arg);
}

and use it like this --for instance--:

foo(2, [](int i) -> void { cout << i << endl; });

Why can't the compiler deduce the type since it's definitely an int?

I get 'void foo(ArgT,boost::function<void(ArgT)>)' : could not deduce template argument for 'boost::function<void(ArgT)>' from 'anonymous-namespace'::<lambda0>'.

解决方案

While C++ lambdas are strictly monomorphic, they are merely shorthand for function objects (aka functors), and in general functors can be polymorphic; i.e., their call operators can be overloaded or templated. As a result, functors (and, consequently, lambdas) are never implicitly convertible to templated std::function<> (or boost::function<>) instances because functors' operator() argument types are not automatically inferable.

To phrase it slightly differently, the natural type of your lambda expression is a functor with a parameterless constructor and an operator() with the signature void operator ()(int) const. However obvious this fact may be to you and I, it's not automatically inferrable that ArgT should resolve to int because lambdas are functors and functors' operator()s are possible to overload and template.

TL;DR: What you want isn't possible.

这篇关于为什么我的C ++编译器不能推导boost函数的模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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