What are templates in C++
Can someone explain this in a simple format?
There are template functions and template classes. What are the advantages and disadvantages? I have heard that templates are slow to build and even at runtime?
True?
开发者_JS百科Thx
In C++ you have the ability to overload functions eg:
void do_something(object1 ob);
void do_something(int i);
Well, templates allow you to make "generic" functions or classes that take arbitrary types. So instead of defining a function each time you add a type, you can define it once, and let the compiler 'write' all the functions for you.
template<typename T>
void do_something(T arg);
With classes you create variants based upon type differences. The best example I can think of is std::vector.. you can think of it as a container/array/whatever of anything. But you need to define the type upfront (so it knows how large each element is, how to copy each element, etc):
std::vector<int> vector_of_ints;
std::vector< std::string > vector_of_strings;
...
Because what is happening, in effect, is the compiler is writing the additional functions for you at compile time, there should not be any runtime effect. The issue at run time might arise though, where you have so much template code, which leads to bloat in the code, and this could lead to execution cache misses... but on today's hardware, that shouldn't be a problem.
The main disadvantage I see is that you have to put templates, generally, in the header file which exposes your implementation. I also find them harder to debug, because they can create quite messy compiler error messages.
To summarize it all up:
If your writing a function add(int a, int b)? Wouldn't it be nice if your add could do it for all datatypes? Not just int without the need to make more than 1 function? That's where templates come in. They make it so you only need one function to encapsulate many types.
This would be how you make the function:
template<typename T>
T add(T a, T b);
精彩评论