Search code examples
c++rvalue-referencervalue

how to understand void (*&&)() func


I use C++ https://cppinsights.io/ to see the progress of instantiation, and there's something puzzled between Function&& and Function.

I comment the code generated by cppinsights.

template<typename Function>
void bind(int type, Function&& func)
{
}

/*
// instantiated from the function above:  
template<>
inline void bind<void (*)()>(int type, void (*&&)() func)
{
}
*/

template<typename Function>
void bindtwo(int type, Function func)
{
}

/*
template<>
inline void bindtwo<void (*)()>(int type, void (*func)())
{
}
*/

void test()
{
    std::cout << "test" << std::endl;
}

int main()
{
    bind(1, &test);
    bindtwo(2, test);
}

Solution

  • how to understand void (*&&)() func

    First things first, the above syntax is wrong because func should appear after the && and not after the () as shown below.

    Now after the correction(shown below), func is an rvalue reference to a pointer to a function that takes no parameter and has the return type of void.

    Note also that the syntax void (*&&)() func is wrong, the correct syntax would be as shown below:

    template<>
    //----------------------------------------------vvvv----->note the placement of func has been changed here
    inline void bind<void (*)()>(int type, void (*&&func)() )
    {
    }