conditional
- C++ course
- Advanced
- Lesson 16/83
- 5 min
Learn compile-time type selection with conditional.
conditional
std::conditional<C, A, B> selects a type at compile time. When C is true it picks A; otherwise it picks B. The result is read via ::type; since C++14 the shortcut std::conditional_t<C, A, B> is preferred.
Example: using T = std::conditional_t<sizeof(int) == 4, int, long>; makes T = int when sizeof(int) == 4, otherwise T = long. This is useful to pick types per platform with no run-time branch.
Use with type aliases
conditional_t is often combined with a using alias. Example: template <typename T> using SmallType = std::conditional_t<sizeof(T) <= 4, int, long>; picks int or long based on the size of T. Then you write SmallType<char>.
This keeps code platform-independent. On 64-bit Linux long is 8 bytes; on 32-bit Windows it is 4 bytes. conditional_t picks by byte size; the user sees the same behaviour on every platform.
Practice Write the SmallType alias
Write template <typename T> using SmallType = std::conditional_t<sizeof(T) <= 4, int, long>;. In main declare SmallType<char> x = 10; and print its size with std::cout << sizeof(x);.
Starter code
#include <iostream>
#include <type_traits>
// Write the SmallType alias
int main() {
// Declare a SmallType<char> variable and print its size
return 0;
}Sample solution
#include <iostream>
#include <type_traits>
template <typename T>
using SmallType = std::conditional_t<sizeof(T) <= 4, int, long>;
int main() {
SmallType<char> x = 10;
std::cout << sizeof(x);
return 0;
}Expected output
4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each expression to its role
| Term | Meaning |
|---|---|
std::conditional_t<C, A, B> |
Type-select shortcut |
std::conditional<C, A, B> |
Type-select template |
::type |
Classic access |
C |
Compile-time condition |
2 Complete the conditional line
template <typename T>
using SmallType = std::____<sizeof(T) <= 4, int, long>;
template <typename T>
using SmallType = std::conditional_t<sizeof(T) <= 4, int, long>;
Explanation: conditional_t<C, A, B> selects a type at compile time.
3 What does conditional_t<true, A, B> pick?
- B
- Neither A nor B
- Compile error
- A Correct answer
Explanation: When the condition is true, the first type (A) is picked.