使用std :: function的隐式转换 [英] Implicit conversions with std::function
问题描述
可能的重复项:
为什么我的C ++编译器无法推断出模板参数增强功能?
不是模板参数(签名)的std :: function类型?
Possible Duplicates:
Why can't my C++ compiler deduce template argument for boost function?
Isn't the template argument (the signature) of std::function part of its type?
我有以下内容:
#include <functional>
void Foo( std::function<void()> );
void Foo( std::function<void(int)> );
void Bar();
int main()
{
Foo( Bar ); // Error: ambiguous
Foo( [](){} ); // Error: ambiguous
Foo( std::function<void()>( Bar ) ); // Ok
Foo( std::function<void()>( [](){} ) ); // Ok
}
我可以使main()的前两行在后两行中不使用函数样式强制转换吗?也许有std :: enable_if解决方案?
Can I make the first two lines in main() work without the function-style cast in the last two lines? Perhaps with a std::enable_if solution?
推荐答案
任何调用参数不完全是std::function<void()>
和std::function<void(int)>
之一的Foo将导致无法解决的重载.甚至是Foo(1)
或Foo("abc")
之类的愚蠢的东西.这是因为std::function
的构造函数是模板化的,并且可以接受任何类型. std::function<void()>(1)
在实例化时会失败,但是重载解析会在实例化之前发生.
Any call to Foo with a parameter which is not exactly one of std::function<void()>
and std::function<void(int)>
will result in an unresolved overloading. Even silly things like Foo(1)
or Foo("abc")
. This is because constructors of std::function
are templated and accept any type. std::function<void()>(1)
would fail at instantiation, but overload resolution happens before instantiation.
因此,不,您需要以一种或另一种方式与这些功能之一进行完全匹配.您可能会引入Foo的其他重载实例,例如
So no, you need to provide an exact match to one of the functions, one way or another. You may introduce other overloaded instances of Foo, like
void Foo(void (*)());
void Foo(void (*)(int));
这将导致更好的匹配,并且不再存在歧义.
and this will result in a better match and the ambiguity will be no more.
这篇关于使用std :: function的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!