I am writing a class template that is parametrized on size_t,
template<size_t k>
class MyClass {...}
The parameter k should really be less than 10, in this case and I would like it to fail to compile if it goes beyond that. How can I do that in C++11 and above?
MyClass<1> instance1; // ok
MyClass<2> instance2; // ok
MyClass<100> instance100; // fail to compile
Use static_assert
template<size_t k>
class MyClass {
static_assert(k < 10, "Illegal k");
};
int main() {
MyClass<50> t; //< Compile time failure
}
You could add a check in the template parameter like
template<size_t k, std::enable_if_t<k <= 10, bool> = true>
class MyClass {};
This will allow MyClass<1> instance1;
but MyClass<100> instance100;
will fail to compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With