C++ SFINAE and Concepts | Template Constraints from C++11 to C++20

C++ SFINAE and Concepts | Template Constraints from C++11 to C++20

이 글의 핵심

Bridge SFINAE-based constraints and C++20 concepts: when substitution fails silently, and how `requires` makes intent explicit.

What is SFINAE?

Substitution Failure Is Not An Error—if substituting template arguments into a signature fails, that overload is discarded rather than necessarily causing an error, as long as another viable candidate exists.

enable_if

Classic pattern to enable declarations only when std::is_* predicates hold—prefer enable_if_t in modern code.

type_traits

is_integral, remove_const, is_same, etc.—building blocks for both SFINAE and concepts.

Concepts (C++20)

#include <concepts>

template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;

template<Numeric T>
T add(T a, T b) {
    return a + b;
}

requires expressions

Express syntactic and semantic requirements on types; compiler checks them at template definition/use sites.

Practical examples

The Korean article includes: container detection SFINAE vs Container concept, callable detection, arithmetic average, Comparable clamp, composite concepts, and improved error messages with concepts.

SFINAE vs concepts

Concepts usually read better and fail with clearer diagnostics—still learn SFINAE for legacy code and library techniques.

Common pitfalls

SFINAE failures when signatures are malformed, circular concept definitions, overly strict ad-hoc concepts.

FAQ

Prefer concepts in new C++20 code; keep SFINAE tools for interoperability and understanding the standard library.


  • Type traits
  • Metaprogramming evolution
  • SFINAE

Keywords

C++, SFINAE, Concepts, templates, metaprogramming.

See also

  • Metaprogramming evolution
  • Advanced metaprogramming
  • Type traits
  • enable_if
  • Expression templates