#include <iostream>
void g(int&) {
std::cout << "int&" << std::endl;
}
void g(int&&) {
std::cout << "int&&" << std::endl;
}
template<typename T>
void func(T&& x) {
std::cout << "func(T&&)\n=================\n";
std::cout << "int: " << std::is_same_v<decltype(x), int> << std::endl;
std::cout << "int&: " << std::is_same_v<decltype(x), int&> << std::endl;
std::cout << "int&&: " << std::is_same_v<decltype(x), int&&> << std::endl;
std::cout << "=================\n";
g(x);
auto tmp = std::move(x);
g(tmp);
g(std::move(x));
}
int main() {
func(2);
}
Output:
func(T&&)
=================
int: 0
int&: 0
int&&: 1
=================
int&
int&
int&&
Why does this code int&&
overloading if I put std::move()
inside of calling g()
function?
I know, that I can solve this problem using std::forward
, but I can't get why it doesn't work.
==================================================
UPDATE: Because of several answers, I have one more question:
In this code:
#include <iostream>
#include <string>
using namespace std;
template<typename T>
void foo(T&& bar){
bar = T();
std::cout << bar;
}
int main() {
foo(22); // OK
foo("qwe"); // NOT OK
}
If I leave foo(22)
, it works great, but it won't work if I leave foo("qwe")
, why?
I tested a lot of cases.