Is the template parameter evaluated at compile time?

I know that templates are a compile-time construct, but what I'm asking about right now is this: suppose I have the following function

void caller1() {
  function(1);
}
void caller2() {
  function(2);
}
void caller3() {
  function(3);
}

void function(int dimensions) {

  if(dimensions <= 0 || dimensions > 3)
     throw out_of_range("Wrong dims");

}

that checking is not a big delay at runtime, but I was wondering if I can replace this function with a template with the parameter "int dimensions" in the template: my question is that it will be solved at compile time and generate code for all three functions called in callers

+4
source share
2 answers

, .

, (), :

template<int N>
typename std::enable_if<(N>0 && N<=3)>::type function() {
     // stuff     
}

, N , :

function<2>(); // OK
function<5>(); // compilation error
+6

Source: https://habr.com/ru/post/1543578/


All Articles