⚙️ C++ Intermediate

What is template specialization and SFINAE in C++?

Why Interviewers Ask This

Mid-level C++ roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

Template specialization provides a custom implementation for a specific type while the general template handles everything else: // Primary template: template<typename T> std::string toString(T value) { return std::to_string(value); } // Full specialization for bool: template<> std::string toString<bool>(bool value) { return value ? "true" : "false"; } // Partial specialization (class templates only): template<typename T> class Container<T*> { // Specialized for pointer types };. SFINAE (Substitution Failure Is Not An Error): when a template substitution fails (e.g., a type doesn't have a member), the compiler silently removes that overload from consideration instead of producing an error. Enables conditional template behavior: // Enable this function only if T is integral: template<typename T> std::enable_if_t<std::is_integral_v<T>, void> process(T value) { std::cout << "Integral: " << value; } // Enabled only for floating point: template<typename T> std::enable_if_t<std::is_floating_point_v<T>, void> process(T value) { std::cout << "Float: " << value; }. C++20 Concepts (replace SFINAE): cleaner syntax: template<std::integral T> void process(T value) { std::cout << "Integral: " << value; } template<std::floating_point T> void process(T value) { std::cout << "Float: " << value; } // Custom concept: template<typename T> concept Printable = requires(T t) { std::cout << t; }; template<Printable T> void print(T value) { std::cout << value; }. Type traits (<type_traits>): compile-time type information: std::is_integral_v<int>, std::is_pointer_v<int*>, std::is_same_v<T, U>, std::decay_t<T>, std::remove_const_t<T>. These are the building blocks of template metaprogramming.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex C++ answers easy to follow.