Quote: Original post by AngleWyrm
Could you give an example of #2, show what is meant by non-type vs type parameter
an example of a non-type template parameter from your hat containers would be:
template <class T, unsigned long (*random)(unsigned long) = std_rand>
talking about the function pointer random, doing this is inflexible, remember that templates are a compile time mechanism
it allows you to perform static polymorphism where as function pointer is a run-time feature it incurs one level of indirection overhead that isn't needed.
if you change it to a type parameter e.g.:
template < typename T, typename Random = std_rand>
then you can use almost anything functors & functions.
Quote:
and how a functor operator() could be advantageous?
its strange that you know STL and you haven't come across functors before, STL use functors alot and they even provide some, mainly in the header functional.
The first reason for the operator() is that when your code realise on that operator then not only can you use types that overload operator() but you can use functions as a type for template type parameter aswell.
the advantage of functors are they are inlineable, they can maintain state, they can be configured through constructors.
Here is really simplified example of a the function generate that first uses the function rand then another call using a functor:
#include <cmath>#include <iterator>#include <algorithm>#include <functional>#include <vector>#include <iostream>struct Random { int operator()() const { return ::rand(); } };template< typename T, typename Iter>void print_elems(Iter beg, Iter end) { std::copy(beg, end, std::ostream_iterator<T>(std::cout, ", "));} int main() { std::vector<int> vec_of_ints(10); //using a function rand std::generate(vec_of_ints.begin(), vec_of_ints.end(), ::rand); print_elems<int>(vec_of_ints.begin(), vec_of_ints.end()); //using a functor Random std::generate(vec_of_ints.begin(), vec_of_ints.end(), Random()); std::cout << "\n\n"; print_elems<int>(vec_of_ints.begin(), vec_of_ints.end()); return 0;}
std::generate uses a type parameter for the Generator type and not a non-type parameter, you can use anything that supports the function call operator () that includes functions this is static polymorphism.
[Edited by - snk_kid on September 1, 2004 3:28:34 AM]