Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write code to do conditional template instantiation in C++

Tags:

c++

templates

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
like image 517
dhu Avatar asked Dec 02 '22 10:12

dhu


2 Answers

Use static_assert

template<size_t k>
class MyClass {
    static_assert(k < 10, "Illegal k");
};

int main() {
  MyClass<50> t; //< Compile time failure
}
like image 69
cplusplusrat Avatar answered Dec 03 '22 23:12

cplusplusrat


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.

like image 36
NathanOliver Avatar answered Dec 03 '22 22:12

NathanOliver