Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a template parameter evaluated at compile time?

Tags:

c++

I know that templates are a compile-time construct but what I'm asking myself right now is: 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 check is not a big delay at runtime, but I was wondering if I could replace that function with a templated one with an "int dimensions" parameter to the template: my question is if that would be solved at compile time and generate code for all three functions called in the callers

like image 293
user129506 Avatar asked Jun 06 '14 15:06

user129506


2 Answers

If an expression is not compile time evaluated it can't be a template parameter.

Your construct can be modified to perform a compile time evaluation, but that wouldn't result in runtime error (exception) but a compilation error :

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

but that would require the dimensions N to be known at compile time, so that you'd call the function like this :

function<2>(); // OK
function<5>(); // compilation error
like image 78
Nikos Athanasiou Avatar answered Sep 25 '22 12:09

Nikos Athanasiou


That would work, as long as the dimensions parameter is always known at compile-time. See http://eli.thegreenplace.net/2011/04/22/c-template-syntax-patterns/ for some descriptions of using templates in ways other than the usual "make this container flexible".

like image 24
Tom Panning Avatar answered Sep 25 '22 12:09

Tom Panning