Reputation: 1334
I yesterday read about Expression Parameters in C++ : http://www.learncpp.com/cpp-tutorial/144-expression-parameters-and-template-specialization/
I know why you use templates, but why use Expression Parameters when you can just use the constructor to accomplish the same thing? Oh, and one more thing, are templates handled by the precompiler?
Thank You in Advance.
Upvotes: 2
Views: 138
Reputation: 66194
The second part of your question first: No, templates are compiled; not preprocessed.
Regarding the first part, they are incredibly useful. The best (and simplest) example of an expression parameter that lends itself with great functionality in templates is size limitations on a static arrays:
#include <iostream>
using namespace std;
template<typename T, size_t N>
void DoSomething(const T (&ar)[N])
{
for (size_t i=0; i<N; ++i)
cout << ar[i] << endl;
}
int main(int argc, char *argv[])
{
int int_ar[] = { 1,2,3,4,5 };
DoSomething(int_ar);
char char_ar[] = {'a', 'b', 'c'};
DoSomething(char_ar);
std::string str_ar[] = {"This", "is", "a", "string", "array."};
DoSomething(str_ar);
return EXIT_SUCCESS;
}
Output
1
2
3
4
5
a
b
c
This
is
a
string
array.
Such things are not possible without expression parameters. They are incredibly useful, especially for things that require size-deduction.
Upvotes: 1
Reputation: 238
When you use a template class it will be expanded at compile time and then compiled like a normal class. One reason to use an expression parameter instead of a parameter in a constructor is that the expression becomes part of the type. So all objects of that type will be guaranteed to use the same value.
In the example you linked to:
// declare an integer buffer with room for 12 chars
Buffer<int, 12> cIntBuffer;
cIntBuffer is an instance of the class Buffer. It is guaranteed to have a int buffer of size 12. If you had:
Buffer<int> cIntBuffer1(12);
Buffer<int> cIntBuffer2(13);
cIntBuffer1 and cIntBuffer2 are the same type of object, but they have different buffer sizes.
Upvotes: 1
Reputation: 15278
Simple example - C++11 array (and boost had similar before). http://en.cppreference.com/w/cpp/container/array
Static arrays are one case where you can't use variables, but you can use template parameters.
Using constants (template parameters) may be more efficient also in other cases.
Preprocessor doesn't touch templates, it only executes #whatever
lines, expands macros, removes comments etc.
Upvotes: 1