自动构造函数不与< functional>对象 [英] Auto-constructor not working with <functional> objects
问题描述
请考虑以下代码:
class _c {
public:
_c
_c(function< void(void)>);
};
具有为 int定义的两个构造函数的类
和函数< void(void)>
这意味着我现在可以实例化对象这些类像这样:
_c a = _c(0);
_c b = _c([](){});
现在,我声明一个函数接受 _c
object作为参数:
void _f(_c __c){};
现在我可以使用 _c
这样的对象:
_f(_c(0));
_f(_c([](){}));
直到这里,一切都很好。现在,如果我试图调用我的 _f
函数没有明确调用 _c
构造函数,我看到:
_f(0)//因为C ++知道使用_c(int)来构造一个带有0的_c
但
_f [](){})//失败,并且没有调用_f'的匹配函数
不明白为什么会发生这种情况,有人可以解释为什么使用< functional>
类型时不起作用吗?
此外,我正在编译:Apple LLVM版本6.0(clang-600.0.57)(基于LLVM 3.5svn)
当调用 f(0)
时,参数的类型为 int
到 _c
。但是,当你调用 _f([](){})时,会出现一个一般的
< ,参数是lambda类型(由编译器生成),而不是类型
std :: function< void(void)>
。因此,在这种情况下,需要 两次转化。一个从lambda类型到 std :: function< void(void)>
,然后到 _c
转换构造函数)。 这两个步骤的转换是不允许的语言,这就是为什么你的代码不工作。 / p>
解决方案是添加一个模板化的构造函数:
template< typename Functor,typename = decltype(std :: declval< Functor&>()())>
_c(Functor& func);
然后你的代码应该工作。
Consider the following code:
class _c {
public:
_c(int);
_c(function<void(void)>);
};
A class with two constructors defined for an int
and a function<void(void)>
respectively.
Which means that I can now instantiante objects of those class like this:
_c a = _c(0);
_c b = _c([]() {});
Now, I declare a function that takes a _c
object as an argument:
void _f(_c __c) {};
And now I can call this function with my _c
objects like this:
_f(_c(0));
_f(_c([]() {}));
Until here, everything looks good. Now, if I try to call my _f
function without explicity invoking the _c
constructor I see that:
_f(0) // works because C++ knows to construct a _c with an 0 by using _c(int)
but,
_f([]() {}) // fails with 'no matching function for call to _f'
I don't understand why is this happening, could someone please explain why doesn't it work when using a <functional>
type?
Also, I'm compiling with: Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
When you call f(0)
, the argument is of type int
which can convert into _c
. It is usual one-step conversion.
However, when you call _f([]() {})
, the argument is lambda-type (generated by the compiler), not of the type std::function<void(void)>
. So in this case, it needs two conversions — one from lambda-type to std::function<void(void)>
, then to _c
(using the conversion-constructor).
The two-steps conversion is not allowed by the language,which is why your code doesn't work.
The solution is to add a templated constructor as:
template<typename Functor, typename =decltype(std::declval<Functor&>()())>
_c(Functor && func);
Then your code should work.
这篇关于自动构造函数不与< functional>对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!