How do I use SFINAE to conditionally enable code?

SFINAE (Substitution Failures Is Not An Error) is a powerful C++ feature that allows you to conditionally enable or disable templates and functions based on type traits. This technique helps you write more generic and reusable code while preventing compilation errors in certain contexts.

Here's a simple example demonstrating the use of SFINAE to conditionally enable a function based on whether a type is integral or not:

#include #include // Primary template for enable_if template struct MyClass; // Specialization for integral types template struct MyClass::value>::type> { void func() { std::cout << "Integral type!" << std::endl; } }; // Specialization for floating-point types template struct MyClass::value>::type> { void func() { std::cout << "Floating-point type!" << std::endl; } }; int main() { MyClass integerType; integerType.func(); // Output: Integral type! MyClass floatType; floatType.func(); // Output: Floating-point type! return 0; }

SFINAE C++ templates type traits enable_if integral types floating-point types conditional code