Passing object pointer as first argument for a member function: is it standard?

前端 未结 1 1781
时光说笑
时光说笑 2021-01-17 11:36

The following program compiles with both gcc and clang, but is this actually standard C++11 or do both compilers choose to support it for convenience?

struct         


        
1条回答
  •  攒了一身酷
    2021-01-17 12:11

    Yes, that is standard. [func.wrap.func.inv] specifies that the operator()(ArgTypes&&... args)
    of std::function calls

    INVOKE (f, std::forward(args)..., R) (20.8.2), where f is the target object (20.8.1) of *this.

    (Where R is the specified return type.)

    [func.require] defines INVOKE:

    Define INVOKE (f, t1, t2, ..., tN) as follows:

    • (t1.*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is an object of type T or a reference to an object of type T or a reference to an object of a type derived from T;

    • ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is not one of the types described in the previous item;

    • […]

    Note that the trailing R in the call is used for the conversion to R (the return type of the function):

    Define INVOKE (f, t1, t2, ..., tN, R) as INVOKE (f, t1, t2, ..., tN) implicitly converted to R.

    The first and only argument you give is the pointer to the Foo-object. The call to method thus results in the call (void)((*t1).*f)() which is, when written with your given values, equivalent to
    ((*(&myFoo)).&Foo::bar)(), which is equivalent to myFoo.bar().

    0 讨论(0)
提交回复
热议问题