Junior — Middle
How can constraints be imposed on types in template parameters in C++?
sobes.tech AI
Answer from AI
In C++, constraints on types in template parameters can be specified in several ways:
- SFINAE (Substitution Failure Is Not An Error) — using
std::enable_ifand other metafunctions from<type_traits>, you can include or exclude template functions or classes based on type properties.
#include <type_traits>
template<typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
void foo(T value) {
// Implementation for integral types
}
int main() {
foo(10); // OK, int is integral
// foo(3.14); // Compilation error, double is not suitable
}
- Concepts — starting with C++20, concepts can be used for more readable and declarative type constraints.
#include <concepts>
template<std::integral T>
void foo(T value) {
// Implementation for integral types
}
- Static assertions (
static_assert) — inside a template, you can check type properties and generate a compilation error with a message.
#include <type_traits>
template<typename T>
void foo(T value) {
static_assert(std::is_integral_v<T>, "T must be an integral type");
// ...
}
Thus, constraints help make templates safer and more understandable.