Reputation: 638
I was reading some documentation and saw this:
template<class Ret, class... Args>
struct is_function<Ret(Args...) &&> : std::true_type {};
Quoted from: http://en.cppreference.com/w/cpp/types/is_function
How can you have a rvalue reference to a function?
From what I understand, functions don't have storage lifetimes. Could someone explain this? I understand references and pointers but how can you "move" a function?
I wrote this code and it compiles and runs as it should:
#include <iostream>
using namespace std;
int foo(int num) {
return num + 1;
}
int main() {
int (*bar1)(int) = &foo;
cout << bar1(1) << endl;
int (&bar2)(int) = foo;
cout << bar2(2) << endl;
auto bar3 = std::move(bar2); // ????
cout << bar3(3) << endl;
cout << bar2(2) << endl;
int (&&bar4)(int) = foo; // ????
cout << bar4(4) << endl;
}
Lets just say if you could store functions as bytecode/opcodes in memory, and 'move' that around. Wouldn't the CPU prevent it from running?
EDIT: @NicolBolas corrected my misunderstanding, but here is an answer for my other 'question': rvalue reference to function
Upvotes: 0
Views: 169
Reputation: 473352
How can you have a rvalue reference to a function?
That's not what that means.
The &&
at the end of Ret(Args...) &&
refers to the ability for a member function to have an rvalue this
. So that specialization works for a function type that has Ret
as the return value, Args
as its arguments, and uses an rvalue this
.
So it's not an "rvalue reference to a function". It's a function that takes an rvalue this
.
Upvotes: 4