Why is 'X x; x();' allowed, when 'X' defines a conversion to function pointer, but not, when it defines a conversion to a functor?

余生颓废 提交于 2019-11-29 16:02:01

问题


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 ?!
}

Live example on Ideone. Output:

error: no match for call to '(Y) (int)'

Q1: Why is the call to x(5) allowed, even though X only defines a conversion to function pointer, and not operator()?

Q2: Conversely, why is the same thing not allowed, if we define a conversion to another functor?


回答1:


x(5); // works ?!

This implicitly casts x to an f_ptr and calls that. C++11 standard:

§ 13.3.1.1.2 Call to object of class type [over.call.object]

2) In addition, for each non-explicit conversion function declared in T of the form

operator conversion-type-id ( ) attribute-specifier-seqopt cv-qualifier ;

[…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);


来源:https://stackoverflow.com/questions/8873048/why-is-x-x-x-allowed-when-x-defines-a-conversion-to-function-pointer-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!