问题描述
void f(int){} typedef void (*f_ptr)(int); struct Functor{ void operator()(int){} }; struct X{ operator f_ptr(){ return f; } }; struct Y{ operator Functor(){ return Functor(); } }; int main(){ X x; Y y; x(5); // works ?! y(5); // doesn't ?! }
。输出:
Q1:为什么允许调用 x(5),即使 X 只定义转换为函数指针,而不是 operator()?
Q1: Why is the call to x(5) allowed, even though X only defines a conversion to function pointer, and not operator()?
Q2:相反,为什么同样的东西不允许,如果我们定义一个转换到另一个函子?
推荐答案
x(5); // works ?!
这会隐式地将 x 转换为 f_ptr 并调用它。 C ++ 11标准:
This implicitly casts x to an f_ptr and calls that. C++11 standard:
operator conversion-type-id ( ) attribute-specifier-seqopt cv-qualifier ;
[...其中 conversion-type-id 表示(P1,...,Pn)的函数的类型指针返回 R ...] p>
[…where conversion-type-id denotes the type "pointer to function of (P1,...,Pn) returning R"…]
y(5); // doesn't ?!
标准没有提及任何关于重载的类类型的隐式转换,
The standard doesn't mention anything about implicit conversion to class types that overload operator() (aka functors), which implies that the compiler doesn't allow that.
你必须显式地强制转换:
You must cast it explicitly:
static_cast<Functor>(y)(5);
这篇关于为什么是'X x; X();'允许,当'X'定义一个转换为函数指针,但不是,当它定义一个转换为函子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!