C++ SFINAE와 Concepts | "템플릿 제약" 가이드
이 글의 핵심
C++ SFINAE와 Concepts에 대한 실전 가이드입니다.
SFINAE란?
Substitution Failure Is Not An Error
- 템플릿 인자 치환 실패는 에러가 아님
- 컴파일러가 다른 오버로드를 찾음
// 정수 타입용
template<typename T>
typename enable_if<is_integral<T>::value, T>::type
process(T value) {
return value * 2;
}
// 실수 타입용
template<typename T>
typename enable_if<is_floating_point<T>::value, T>::type
process(T value) {
return value * 3.0;
}
int main() {
cout << process(10) << endl; // 20 (정수)
cout << process(3.14) << endl; // 9.42 (실수)
}
enable_if
#include <type_traits>
using namespace std;
// C++11 스타일
template<typename T>
typename enable_if<is_integral<T>::value, void>::type
printType(T value) {
cout << value << " is integral" << endl;
}
// C++14 스타일 (간결)
template<typename T>
enable_if_t<is_integral<T>::value, void>
printType2(T value) {
cout << value << " is integral" << endl;
}
// C++17 스타일 (더 간결)
template<typename T, enable_if_t<is_integral_v<T>, int> = 0>
void printType3(T value) {
cout << value << " is integral" << endl;
}
type_traits
// 타입 체크
is_integral<int>::value // true
is_floating_point<double>::value // true
is_pointer<int*>::value // true
is_const<const int>::value // true
// 타입 변환
remove_const<const int>::type // int
add_pointer<int>::type // int*
decay<int[10]>::type // int*
// 타입 관계
is_same<int, int>::value // true
is_base_of<Base, Derived>::value // true
is_convertible<int, double>::value // true
Concepts (C++20)
#include <concepts>
// 기본 concept
template<typename T>
concept Numeric = integral<T> || floating_point<T>;
template<Numeric T>
T add(T a, T b) {
return a + b;
}
// 커스텀 concept
template<typename T>
concept Printable = requires(T t) {
{ cout << t } -> convertible_to<ostream&>;
};
template<Printable T>
void print(T value) {
cout << value << endl;
}
int main() {
cout << add(1, 2) << endl; // OK
cout << add(1.5, 2.5) << endl; // OK
// cout << add("a", "b"); // 에러
}
requires 표현식
// requires 절
template<typename T>
requires integral<T> || floating_point<T>
T multiply(T a, T b) {
return a * b;
}
// requires 표현식
template<typename T>
concept HasSize = requires(T t) {
{ t.size() } -> convertible_to<size_t>;
};
template<HasSize T>
void printSize(const T& container) {
cout << "크기: " << container.size() << endl;
}
실전 예시
예시 1: 컨테이너 타입 체크
// SFINAE 버전
template<typename T>
struct is_container {
private:
template<typename U>
static auto test(int) -> decltype(
declval<U>().begin(),
declval<U>().end(),
true_type{}
);
template<typename>
static false_type test(...);
public:
static constexpr bool value = decltype(test<T>(0))::value;
};
template<typename T>
enable_if_t<is_container<T>::value, void>
print(const T& container) {
for (const auto& item : container) {
cout << item << " ";
}
cout << endl;
}
// Concepts 버전 (C++20)
template<typename T>
concept Container = requires(T t) {
t.begin();
t.end();
};
template<Container T>
void printContainer(const T& container) {
for (const auto& item : container) {
cout << item << " ";
}
cout << endl;
}
예시 2: 함수 호출 가능 체크
// SFINAE
template<typename Func, typename... Args>
struct is_callable {
private:
template<typename F, typename... A>
static auto test(int) -> decltype(
declval<F>()(declval<A>()...),
true_type{}
);
template<typename, typename...>
static false_type test(...);
public:
static constexpr bool value = decltype(test<Func, Args...>(0))::value;
};
// Concepts
template<typename Func, typename... Args>
concept Callable = requires(Func f, Args... args) {
f(args...);
};
template<Callable<int, int> Func>
int apply(Func f, int a, int b) {
return f(a, b);
}
int main() {
auto add = { return a + b; };
cout << apply(add, 1, 2) << endl; // 3
}
예시 3: 산술 연산 지원 체크
// Concepts
template<typename T>
concept Arithmetic = requires(T a, T b) {
{ a + b } -> convertible_to<T>;
{ a - b } -> convertible_to<T>;
{ a * b } -> convertible_to<T>;
{ a / b } -> convertible_to<T>;
};
template<Arithmetic T>
T average(const vector<T>& values) {
T sum = T{};
for (const T& v : values) {
sum = sum + v;
}
return sum / values.size();
}
int main() {
vector<int> ints = {1, 2, 3, 4, 5};
cout << average(ints) << endl; // 3
vector<double> doubles = {1.5, 2.5, 3.5};
cout << average(doubles) << endl; // 2.5
}
예시 4: 비교 가능 타입
template<typename T>
concept Comparable = requires(T a, T b) {
{ a < b } -> convertible_to<bool>;
{ a > b } -> convertible_to<bool>;
{ a == b } -> convertible_to<bool>;
};
template<Comparable T>
T clamp(T value, T min, T max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
int main() {
cout << clamp(5, 0, 10) << endl; // 5
cout << clamp(-5, 0, 10) << endl; // 0
cout << clamp(15, 0, 10) << endl; // 10
}
SFINAE vs Concepts
// SFINAE (복잡)
template<typename T>
typename enable_if<
is_integral<T>::value && is_signed<T>::value,
T
>::type
abs(T value) {
return value < 0 ? -value : value;
}
// Concepts (간결)
template<typename T>
concept SignedIntegral = integral<T> && signed_integral<T>;
template<SignedIntegral T>
T abs(T value) {
return value < 0 ? -value : value;
}
복합 Concepts
template<typename T>
concept Number = integral<T> || floating_point<T>;
template<typename T>
concept SignedNumber = Number<T> && signed_integral<T>;
template<typename T>
concept Container = requires(T t) {
typename T::value_type;
{ t.begin() } -> same_as<typename T::iterator>;
{ t.end() } -> same_as<typename T::iterator>;
{ t.size() } -> convertible_to<size_t>;
};
template<typename T>
concept NumericContainer = Container<T> && Number<typename T::value_type>;
자주 발생하는 문제
문제 1: SFINAE 실패
// ❌ SFINAE 실패
template<typename T>
typename T::value_type get(T container) { // T가 int면?
return container[0];
}
// ✅ enable_if 사용
template<typename T>
enable_if_t<is_class<T>::value, typename T::value_type>
get(T container) {
return container[0];
}
문제 2: Concept 순환 의존
// ❌ 순환 의존
template<typename T>
concept A = B<T>;
template<typename T>
concept B = A<T>;
// ✅ 명확한 정의
template<typename T>
concept A = integral<T>;
template<typename T>
concept B = A<T> && signed_integral<T>;
문제 3: 과도한 제약
// ❌ 너무 제약적
template<typename T>
concept StrictNumber = integral<T> && sizeof(T) == 4;
// ✅ 적절한 제약
template<typename T>
concept Number = integral<T> || floating_point<T>;
에러 메시지 개선
// SFINAE (에러 메시지 복잡)
template<typename T>
enable_if_t<is_integral<T>::value, void>
process(T value) {
// ...
}
// Concepts (에러 메시지 명확)
template<integral T>
void process(T value) {
// ...
}
// 커스텀 에러 메시지
template<typename T>
concept Positive = requires(T t) {
requires t > 0; // "requires t > 0 is not satisfied"
};
FAQ
Q1: SFINAE vs Concepts?
A: C++20 이상이면 Concepts를 사용하세요. 더 읽기 쉽고 에러 메시지가 명확합니다.
Q2: 언제 SFINAE를 사용하나요?
A:
- C++17 이하
- 레거시 코드베이스
- 라이브러리 호환성
Q3: Concepts는 성능에 영향을 주나요?
A: 아니요. 컴파일 타임에만 체크되므로 런타임 오버헤드가 없습니다.
Q4: Concepts를 어떻게 배우나요?
A:
- 표준 concepts 사용 (integral, floating_point 등)
- 간단한 커스텀 concept 작성
- 복합 concept 작성
Q5: SFINAE 디버깅은?
A:
- static_assert 사용
- Compiler Explorer 활용
- 에러 메시지 주의 깊게 읽기
Q6: Concepts 학습 리소스는?
A:
- cppreference.com
- “C++20: The Complete Guide”
- Compiler Explorer (godbolt.org)
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ Type Traits | “타입 특성” 완벽 가이드
- C++ 메타프로그래밍의 진화: Template에서 Constexpr, 그리고 Reflection까지
- C++ SFINAE | “Substitution Failure Is Not An Error” 가이드
관련 글
- C++ 메타프로그래밍의 진화: Template에서 Constexpr, 그리고 Reflection까지
- C++ 메타프로그래밍 고급 | SFINAE·Concepts·constexpr·타입 트레이트 가이드
- C++ Type Traits |
- C++ enable_if |
- C++ Expression Templates |