2.7 KiB
2.7 KiB
Templates
Knowledge check
Template type deduction
template <typename T>
void copy(T arg) {}
template <typename T>
void reference(T& arg) {}
template <typename T>
void universal_reference(T&& arg) {}
int main() {
int number = 4;
copy(number); // int
copy(5); // int
reference(number); // int&
reference(5); // candidate function [with T = int] not viable: expects an l-value for 1st argument
universal_reference(number); // int&
universal_reference(std::move(number)); // int&&
universal_reference(5); // int&&
}
Knowledge check
void foo(int && a); // r
void foo(int & a); // l
int a = 5;
Which of above functions will be called by below snippets?
-
foo(4);- r
-
foo(a);- l
-
foo(std::move(a));- r
-
foo(std::move(4));- r (move is redundant)
Knowledge check
template <typename T>
void foo(T && a); // r
template <typename T>
void foo(T & a); // l
int a = 5;
Which of above functions will be called by below snippets?
-
foo(4);- r
-
foo(a);- l
-
foo(std::move(a));- r
Knowledge check
template <typename T>
void foo(T && a); // r
int a = 5;
What will happen now?
-
foo(4);- r
-
foo(a);- r
-
foo(std::move(a));- r