I read about meta-programming, and found it was really interesting. For example, check to see if the number is prime, calculate fibonacci number...I'm curious about its practical usage, if we can convert all runtime solution to meta-programming, the the application would perform much better. Let's say to find max value of an array. We would take O( n ) at run time if it was not sorted. Is it possible to get O( 1 ) with meta-programing?
Thanks,
Chan
You can't because metaprogramming only works for inputs that are known at compile time. So you can have a metafunction that calculates a Fibonacci number given a constant known at compile time:
int value = Fibonacci<5>::Value;
But it won't work for values that are inputted by a user at runtime:
int input = GetUserInput();
int value = Fibonacci<input>::Value; // Does not compile
Sure, you can recompile the program every time you get new values, but that becomes impractical for non-trivial programs.
Keep in mind that metaprogramming in C++ is basically a "useful accidental abuse" of the way C++ handles templates. Template metaprogramming was definitely not what the C++ standards committee had in mind when creating the C++ standards prior to C++0x. You can only push the compiler so much until you get internal compiler errors (that has changed nowadays with newer compilers, but you still shouldn't go overboard).
There's an (advanced-level) book dedicated to C++ template metaprogramming if you want to see what they are really useful for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With