What happens passing function name by value, lvalue reference and rvalue reference?

144 Views Asked by At

I'm not sure exact mechanism of rvalue and lvalue in a various case. Let me example it.

#include <iostream>

void f() { std::cout << "Hello\n"; }

template<typename T>
void g0(T&& a) {
    a();
}

template<typename T>
void g1(T& a) {
    a();
}

template<typename T>
void g2(T a) {
    a();
}

int main() {

    printf("%p, %p\n", f, &f); // f and &f are same

    g0(f); // (1)
    g0(&f); // (2)

    g1(f); // (3)
//    g1(&f); // (4) compile error !!

    g2(f); // (5)
    g2(&f); // (6)
}

My questions

  1. Both function name f and & before f(=> &f) are just function pointer. Am I correct ?
  2. What happens when I passing function name or & with function name to argument of various function such as (1), (2), (3), (4), (5), (6) ?
  3. (4) has compile error. f and &f are same under my understanding but why does it happen? I know it can be compiled if I use const such as "void g1(const T& a)" but I'm not sure why.

The error message is:

candidate function [with T = void (*)()] not viable: no known conversion from 'void (*)()' to 'void (*&)()' for 1st argument
void g1(T& a)...
0

There are 0 best solutions below