1. What does "template instantiation" refer to?
2. What will the following code snippet output? int x = 5; auto my_lambda = [x]() { x += 1; std::cout << x << " "; }; my_lambda(); my_lambda(); std::cout << x << std::endl;
int x = 5;
auto my_lambda = [x]() {
x += 1;
std::cout << x << " ";
};
my_lambda();
std::cout << x << std::endl;
3. What is the type of the captured variable in the following lambda? const double pi = 3.14; auto get_area = [pi](int r){ return std::to_string(pi * r * r); };
const double pi = 3.14;
auto get_area = [pi](int r){
return std::to_string(pi * r * r);
std::string
const double
const int
4. What is an explicit specialization of a template?
5. Which of that following is a potential downside of excessive use of templates, even when fully adhering to the C++ standard?
6. Given the following function template: template <typename T> bool CompareToZero(T in) { return in == static_cast<T>(0); } Which function call will NOT cause a compilation error?
template <typename T>
bool CompareToZero(T in) {
return in == static_cast<T>(0);
}
CompareToZero(0, 0);
CompareToZero(std::vector<int>{0});
CompareToZero('c');
CompareToZero<std::string>("12");
7. Consider this code: template <typename T=int> T getValue() { return T(); } What will getValue() return if called without any arguments?
template <typename T=int>
T getValue() {
return T();
'a'
""
'\0'
8. Consider the function template: template <typename T> void func(T arg) { /* ... */ } If you call func(42), what will be the type of T?
void func(T arg) { /* ... */ }
func(42)
T
int
int&
void
int*
arg
9. In which of the following scenarios is the typename keyword mandatory to disambiguate a declaration?
typename
10. Given the following function template: template <typename T> void Print(const T & item) { std::cout << item << std::endl; } Which call to Print would cause a compile-time error?
void Print(const T & item) {
std::cout << item << std::endl;
Print
Print("This is my literal string");
Print(22);
Print(x)
x
std::map<std::string, std::string>
Print(nullptr);
Click Check Answers to identify any errors and try again. Click Show Answers if you also want to know which answer is the correct one.