Hoisting the dynamic type out of a loop (a.k.a. doing Java the C++ way)

后端 未结 4 860
清歌不尽
清歌不尽 2020-12-06 05:23

I was discussing the merits of \"modern\" languages compared to C++ with some friends recently, when the following came up (I think inspired by Java):

Does any C++ c

4条回答
  •  半阙折子戏
    2020-12-06 06:01

    It has been pointed out to me that GCC has an extension, called "bound member functions", that does indeed allow you to store the actual function pointer. Demo:

    struct Foo
    {
        virtual ~Foo() { }
        virtual int f(int, int) = 0;
    };
    
    void f(Foo & x)
    {
        using gcc_func_type = int (*)(Foo *, int, int);
    
        gcc_func_type fp = (gcc_func_type)(x.*&Foo::f);  // !
    
        for ( /* ... */ )
        {
            int result = fp(&x, 10, 20);   // no virtual dispatch!
        }
    }
    

    The syntax requires that you go through a pointer-to-member indirection (i.e. you cannot just write (x.f)), and the cast must be a C-style cast. The resulting function pointer has the type of a pointer to a free function, with the instance argument taken as the first parameter.

提交回复
热议问题