The whole book test
-
-
- [Multiple-Choice Questions](#Multiple-Choice Questions)
- [Answers and Explanations](#Answers and Explanations)
- [C++20 Programming Challenges](#C++20 Programming Challenges)
- [Solutions & Explanations](#Solutions & Explanations)
-
Multiple-Choice Questions
-
Which of the following are advantages of C++20 Concepts?
a) Improved error messages during template instantiation
b) Automatic memory management for templates
c) Enable function overloading based on semantic constraints
d) Elimination of header files
-
Which syntax forms are valid for defining a function template using Concepts?
a)
template <std::integral T> T add(T a, T b)b)
auto add(std::integral auto a, std::integral auto b)c)
void add(T a, T b) requires std::integral<T>d)
std::integral add(std::integral a, std::integral b) -
What are the key benefits of C++20 Modules?
a) Faster compilation times due to reduced header redundancy
b) Isolation of preprocessor macros across modules
c) Automatic parallel execution of code
d) Elimination of the One Definition Rule (ODR)
-
Which statements about
std::spanare correct?a) It owns the elements it references.
b) It can automatically deduce the size of a contiguous sequence.
c) It is a replacement for
std::vector.d) It supports both static and dynamic extents.
-
What is true about the
constevalspecifier in C++20?a) It ensures a function is evaluated at runtime.
b) It implicitly makes a function
constexpr.c) It can only be applied to virtual functions.
d) It guarantees compile-time evaluation for every invocation.
-
Which features are part of the C++20 Ranges library?
a) Lazy evaluation of operations
b) Direct container manipulation without iterators
c) Thread-safe container operations
d) Pipeline syntax using the
|operator -
What are valid uses of the
[[nodiscard]]attribute?a) To enforce error checking for function return values
b) To optimize compiler-generated code
c) To mark deprecated functions
d) To suppress compiler warnings for unused variables
-
Which statements about
std::jthreadare correct?a) It automatically joins its thread upon destruction.
b) It supports cooperative interruption via
std::stop_token.c) It is a drop-in replacement for
std::threadwith identical behavior.d) It requires manual resource management.
-
What is true about the Three-Way Comparison Operator (
<=>)?a) It can be defaulted to generate all six comparison operators.
b) It returns a boolean value.
c) It requires manual implementation for derived classes.
d) It supports lexicographical comparison of class members.
-
Which operations are valid for
std::atomic_ref?a) Atomic updates on non-atomic objects
b) Thread-safe access to subobjects of the referenced object
c) Guaranteed lock-free implementation
d) Cooperative interruption of threads
-
What is true about
constinit?a) It ensures constant initialization for static storage duration variables.
b) It implies
constexpr.c) It can be applied to dynamically allocated memory.
d) It solves the static initialization order fiasco.
-
Which statements about Coroutines are correct?
a) They require manual stack management.
b)
co_awaitsuspends execution until a result is available.c)
co_yieldreturns a value and resumes execution later.d) They are exclusively for multi-threaded applications.
-
What are valid uses of
requiresclauses?a) To constrain template parameters using logical combinations of concepts
b) To define runtime preconditions for functions
c) To specify exception guarantees
d) To check the validity of expressions at compile time
-
Which features are part of the C++20 Calendar and Time Zone library?
a) Time zone-aware time points
b) Mathematical constants like π
c) Literals for days (
d) and years (y)d) Formatting utilities for dates
-
What is true about the
std::formatlibrary?a) It uses Python-style format strings.
b) It is type-safe compared to
printf.c) It requires manual memory allocation for output.
d) It supports user-defined types via specialization.
-
Which statements about Lambda improvements in C++20 are correct?
a) Lambdas can have template parameters.
b) Stateless lambdas can be default-constructed.
c) Lambdas cannot capture
thisimplicitly.d)
constevallambdas are evaluated at runtime. -
What is true about
std::semaphorein C++20?a) It supports both counting and binary semaphores.
b) It is part of the
<thread>header.c) It replaces
std::mutexfor all use cases.d) Its
acquire()method decrements the counter. -
Which statements about Designated Initialization are correct?
a) It allows initializing class members in any order.
b) It works only with aggregate types.
c) It is compatible with private class members.
d) Missing designators result in zero-initialization.
-
What is true about the
std::rangesalgorithms?a) They operate directly on containers without iterators.
b) They are always evaluated eagerly.
c) They support pipeline composition using
|.d) They replace all existing
<algorithm>functions. -
Which statements about
std::stop_sourceandstd::stop_tokenare correct?a) They enable cooperative thread cancellation.
b) A
stop_tokencan be used to poll for cancellation requests.c) They are part of the
<atomic>header.d)
std::jthreadautomatically managesstop_sourcelifetime. -
What is true about the
no_unique_addressattribute?a) It allows overlapping storage for empty class members.
b) It guarantees unique memory addresses for all members.
c) It is used to optimize space in class layouts.
d) It applies only to virtual base classes.
-
Which statements about
std::latchandstd::barrierare correct?a)
std::latchcan be reused multiple times.b)
std::barriersupports phase-based synchronization.c) Both are defined in the
<semaphore>header.d)
std::latchdecrements a counter on eacharrive_and_wait(). -
What is true about the
std::source_locationclass?a) It provides compile-time information about the source code.
b) It replaces the
__FILE__and__LINE__macros.c) It requires runtime computation to capture location data.
d) It is part of the
<format>header. -
Which statements about the Spaceship Operator (
<=>) are correct?a) It returns a value of type
std::strong_ordering.b) It can be used to generate equality operators (
==,!=).c) It requires explicit implementation for all comparison categories.
d) It simplifies the definition of comparison operators for classes.
-
What is true about the
std::is_constant_evaluated()function?a) It returns
trueduring compile-time evaluation.b) It is used to optimize runtime performance.
c) It can differentiate between
constexprandconstevalcontexts.d) It is part of the
<type_traits>header.
Answers and Explanations
-
a, c
Concepts improve error messages and enable overloading based on constraints (Section 4.1.2). Modules eliminate headers, not Concepts.
-
a, b, c
Valid syntax includes constrained templates, abbreviated function templates, and trailing
requiresclauses (Section 4.1.4). Option d is invalid. -
a, b
Modules reduce header redundancy and isolate macros (Section 4.2.2). ODR still applies.
-
b, d
std::spandeduces size and supports static/dynamic extents (Section 5.2.1). It does not own elements. -
b, d
constevalensures compile-time evaluation and is a subset ofconstexpr(Section 4.5.1). -
a, b, d
Ranges support lazy evaluation, direct container ops, and pipeline syntax (Section 5.1).
-
a
[[nodiscard]]enforces checking return values (Section 4.8.1). It does not optimize code or mark deprecation. -
a, b
std::jthreadauto-joins and supports interruption (Section 6.6). It is not identical tostd::thread. -
a, d
<=>can be defaulted for lexicographical comparisons (Section 4.3.4). It returns an ordering type, not a boolean. -
a
std::atomic_refapplies atomic ops to non-atomic objects (Section 6.2.1). Subobjects are not thread-safe. -
a, d
constinitensures compile-time initialization and avoids static order issues (Section 4.5.4). It does not implyconstexpr. -
b, c
Coroutines use
co_await/co_yieldfor suspension/resumption (Section 6.1). They are not limited to multi-threading. -
a, d
requiresclauses constrain templates and validate expressions (Section 4.1.9). They are not for runtime checks. -
a, c
The library includes time zones and literals (Section 5.6). Formatting is separate.
-
a, b, d
std::formatuses Python syntax, is type-safe, and supports custom types (Section 5.5). -
a, b
Lambdas support templates and stateless default construction (Section 4.7).
thiscapture detection is improved. -
a, d
Semaphores are counting and use
acquire()(Section 6.3). They are in<semaphore>. -
b, d
Designated initialization works with aggregates and zero-initializes missing fields (Section 4.4).
-
a, c
Ranges operate on containers and support pipelines (Section 5.1). Evaluation can be lazy.
-
a, b, d
stop_source/tokenenable cancellation and are managed byjthread(Section 6.5). -
a, c
no_unique_addressoptimizes space for empty members (Section 4.8.3). -
b, d
barriersupports phases;latchdecrements a counter (Section 6.4). They are in<latch>/<barrier>. -
a, b
std::source_locationreplaces macros and is compile-time (Section 5.7.4). It is in<source_location>. -
a, b, d
<=>returns ordering categories and simplifies operator definitions (Section 4.3). Categories are automatic. -
a, d
is_constant_evaluated()detects compile-time context (Section 5.7.2). It is in<type_traits>.
C++20 Programming Challenges
- Constrained Matrix Multiplication with Concepts
Problem : Implement a matrix multiplication function using concepts to ensure input matrices satisfy mathematical requirements (contiguous containers, compatible dimensions). Test withstd::vector<std::vector<T>>and invalid types.
Key Points:
- Use
std::ranges::contiguous_rangeand custom dimension checks. - Leverage
requiresclauses for template constraints.
- Module-Based Math Library
Problem : Create a C++20 modulemaththat exportsadd,multiply, andpowerfunctions. Import the module in another translation unit and verify symbol visibility.
Key Points:
- Module interface vs. implementation partitions.
- Export control and name visibility rules.
- Lazy Prime Number Generator with Ranges
Problem : Generate an infinite sequence of prime numbers using range views (filter+transform). Extract the first 20 primes and print them.
Key Points:
- Compose range adaptors with
|operator. - Lazy evaluation for infinite sequences.
- Custom Coroutine-Based Event Loop
Problem : Implement an event loop using coroutines that processes tasks cooperatively. Schedule async I/O simulations withco_await.
Key Points:
- Coroutine state machine mechanics.
co_awaitfor suspension/resumption.
- Spaceship Operator for Complex Numbers
Problem : Define aComplexclass with compiler-generatedoperator<=>and test ordering in sorted containers.
Key Points:
defaulted three-way comparison.- Strong/weak/partial ordering scenarios.
- Type-Safe Heterogeneous Collection with
std::span
Problem : Usestd::spanto create a function that processes elements from different containers (std::array,std::vector) without copying.
Key Points:
std::span's bounds checking.- Contiguous memory requirements.
- Compile-Time JSON Parser with
constexpr
Problem : Build aconstexprJSON parser that validates syntax and extracts values at compile time. Test with static assertions.
Key Points:
constevalfor strict compile-time execution.- Recursive constexpr parsing.
- Thread-Safe FIFO Queue with Semaphores
Problem : Implement a FIFO queue using C++20std::counting_semaphoreto enforce thread-safe producer-consumer access.
Key Points:
- Semaphore acquire/release mechanics.
- RAII wrappers for exception safety.
- Atomic Shared State with
std::atomic<std::shared_ptr>
Problem : Create a thread-safe global counter usingstd::atomic<std::shared_ptr<int>>and verify atomic updates.
Key Points:
- Atomic smart pointer operations.
- Memory ordering guarantees.
- Timezone-Aware Meeting Scheduler
Problem : Use<chrono>to schedule meetings across time zones (e.g., "New York 9:00 AM" to "London" local time).
Key Points:
std::chrono::time_zoneconversions.- Daylight saving time handling.
- CRTP with Non-Type Template Parameters
Problem: Implement Curiously Recurring Template Pattern (CRTP) using NTTPs to create compile-time polymorphic counters.
Key Points:
- NTTP type restrictions (structural types).
- Compile-time polymorphism.
- Fold Expressions with Variadic Concepts
Problem : Write aconcatfunction using fold expressions and concepts to ensure all arguments are string-like (std::string,std::string_view).
Key Points:
- Variadic templates with constrained
auto. - Concept-based overloading.
- Stateful Lambda Pipeline with
std::views
Problem: Create a range pipeline that tracks state between iterations (e.g., moving average of last 3 elements).
Key Points:
- Stateful lambda captures.
- Range view composition challenges.
- Custom Formatter for Scientific Notation
Problem : Extendstd::formatterto displaydoublein engineering notation (exponent multiples of 3). Test withstd::format.
Key Points:
- Format string parsing API.
- Locale-independent formatting.
- Barrier-Based Parallel Matrix Transposition
Problem : Transpose a large matrix usingstd::barrierto synchronize worker threads operating on matrix blocks.
Key Points:
- Barrier phase synchronization.
- Thread partitioning and data races.
Solutions & Explanations
Wait for resolution...