c++11 - Why can't I mix C++ universal references with standard reference? -
i'm trying understand c++11's universal references, , wrote following code:
#include <cstdio> template <typename l, typename r> static void run(l&& lhs, const r& rhs) { lhs += rhs; } static void run2(int&& lhs, const int& rhs) { lhs += rhs; } int main() { int = 0; int b = 3; run(a, b); printf("%d\n", a); // not compile. run2(a, b); printf("%d\n", a); return 0; } note run() works, line calling run2() fail compile. can't figure out why. error no known conversion 'int' 'int &&' 1st argument.
i'm sure compiler right, can't figure out under why. seems run() , run2() doing same things right?
btw, changing run2() templated single parameter not work.
"universal references" can happen in contexts type of reference deduced, such in template type context t&&. in case, t can either deduced int rvalue argument, , have int&& argument type; or int& lvalue argument, give type int& && per reference collapsing rules becomes int&. in run2 function, type directly int&& , cannot bind lvalue unless use std::move.
Comments
Post a Comment