C++Guns – RoboBlog

26.07.2015

Replace runtime constant wich template variables

Filed under: Allgemein — Tags: — Thomas @ 09:07

void version1(int i, int h) {
  // if(h) is evaluated every call
  if(h==0) {
  }
  else if(h==1) {
  }
  else {
  }
}

template
void version2(int i) {
  // if(h) is evaluated at compile time
  if(h==0) {
  }
  else if(h==1) {
  }
  else {
  }
}

void func(int h) {
  // h is a runtime constant for this function
  for(int i=0; i < 1e7; ++i) {
    version1(i, h);
  }

  // here,h is evaluated at runtime but outside the loop.
  // the compiler create three different version of version2 each for every h
  if(h==0) {
    for(int i=0; i < 1e7; ++i) {
      version2<0>(i);
    }
  }
  else if(h==1) {
    for(int i=0; i < 1e7; ++i) {
      version2<1>(i);
    }
  }
  else {
    for(int i=0; i < 1e7; ++i) {
      version2<2>(i);
    }
  }
}

int main() {
  int h=0;
  func(h);

  h=1;
  func(h);
}

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress