I am quite new to std::enable_if and wondering how to use it. I have a template class:
template<int a, int b>
class foo {
}
Now I only want to instantiate it when a + b equals to 10. Could I make this possible using std::enable_if?
The second question: If I have a member in class foo
template<int a, int b>
class foo {
int c;
}
I only want to have c when
a = 5.
How do I do that using std::enable_if? Is this one the correct case to use std::enable_if?
I guess you can use static_assert better to enforce that constraint instead of enable_if
enable_if is primarily used to conditionally remove functions and classes from overload resolution based on type traits and to provide separate function overloads and specializations for different type traits.
With C++20
You can achieve that simply by adding
requires
to the template:The
requires
clause gets aconstant expression
that evaluates totrue
orfalse
deciding thus whether to consider this method in the overload resolution, if the requires clause is true, or ignore it otherwise.Code: https://godbolt.org/z/yHh4Et
This should do the job; just make sure you never explicitly provide the third template parameter when instantiating the template.
As others mentioned,
static_assert
is a much better fit.Simple, just don't use
enable_if