Multiple Choice Quiz

1. 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);
  };

2. How does the keyword mutable modify a lambda?

3. Given the following code:
  template <typename T>
  std::string Version(T in) { return "Generic"; }
  template <>
  std::string Version(std::string in) { return "String"; }
What would happen if you ran Version("test")?

4. What does "template instantiation" refer to?

5. How often can the same template function declaration or definition appear in your code? (Hint: template functions are automatically considered inline functions.)

6. What is the difference between template parameters and template arguments?

7. 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?

8. What does a capture of [&] mean for a lambda?

9. Which of the following statements is true when considering the performance of lambdas?

10. Given the class template:
  template <typename T1=std::string, typename T2=int>
  class Pair {
    T1 first;
    T2 second;
  public:
    Pair(T1 a, T2 b) : first(a), second(b) {}
  };
Which of the following is NOT a legal way to declare a variable of type Pair? (Note: template type deduction is not done if angle brackets are provided)

11. Which of the following is a potential downside of excessive use of templates, even when fully adhering to the C++ standard?

12. What will the following code snippet output?
  int x = 5;
  auto my_lambda = [x]() mutable {
    x += 1;
    std::cout << x << " ";
  };
  my_lambda();
  my_lambda();
  std::cout << x << std::endl;

13. Consider this code:
  template <typename T=int>
  T getValue() {
      return T{};
  }
What will getValue() return if called without any arguments?

14. What is my_lambda after the following code is run?
  auto my_lambda = [](int x){ return x+1; };

15. What is the output of the following code snippet?
  std::vector<int> vec{3, 1, -2};
  auto rng = vec
    | std::views::transform([](int j){ return (j % 2 == 0) ? j : 2 * j;})
    | std::views::transform([](int j){ return j*j;});
  for(auto i : rng){
    std::cout << i << " ";
  }
  std::cout << std::endl;

16. What does it mean for a lambda to be "generic"?

17. Which of the following will not compile?
Assume std::vector<int> vec = GetVector();

18. When does capturing occur in a lambda?

19. Consider the function template:
  template <typename T>
  void func(T arg) { /* ... */ }
If you call func(42), what will be the type of T?

20. What is a template specialization?


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.