Thread: template and compiler ?!!

  1. #1

    template and compiler ?!!

    how can I make the compiler do some thing While compiling:
    VIZ : How To make it calculate 1+1(for Example) while it compiling
    not after I run the program???
    and what can the (( template )) aid in this context!

  2. #2
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    #include <iostream>
    template <int n> int compileTimeInt() {
    	return n;
    template <int a, int b> int compileTimeAdd() {
    	return compileTimeInt<a+b>();
    int main() {
    	std::cout << compileTimeAdd<2,5>() << std::endl;
    	return 0;
    That forces the compiler to evaulate the sum at compile time. That said, such an optimization is performed by even the worst optimizing compilers.

    If you want to see some pretty cool IMHO use of templates for compile time optimization, see this post.

    I post a recursive solution to a problem, Sorensen posts an iteritive version, it's limited, though, to a certain size). I post a templated version of Sorensen's code that will expand at compile time to fit any size.

    The compile time stuff is really interesting. Still, sometimes it's a bit hard to read, and it's also sometimes not the useful. But you have to believe using the compiler itself, and not the executable it produces, to do work is an intriguing concept.
    Last edited by SilentStrike; 06-28-2002 at 03:03 AM.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  3. #3
    Thank you Very mach

    But can you explain your anwer sorry but I'm beginner!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. template to let compiler generate zero
    By KIBO in forum C++ Programming
    Replies: 4
    Last Post: 06-15-2009, 03:51 AM
  2. compiler not inferring template type as expected
    By Elkvis in forum C++ Programming
    Replies: 13
    Last Post: 11-12-2008, 06:04 AM
  3. template function v.s. template class
    By George2 in forum C++ Programming
    Replies: 3
    Last Post: 12-13-2007, 01:46 AM
  4. Template compiler pains
    By crypticgeek in forum C++ Programming
    Replies: 13
    Last Post: 08-06-2006, 03:00 PM
  5. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM