I've searched for this question and I can't find anything on it. Is there a better way to query something like this in Google or can anyone provide a link or links or a fairly detailed explanation? Thanks!
EDIT: Here's an example
template< typename T, size_t N> struct Vector { public: Vector() { this->template operator=(0); } // ... template< typename U > typename boost::enable_if< boost::is_convertible< U, T >, Vector& >::type operator=(Vector< U, N > const & other) { typename Vector< U, N >::ConstIterator j = other.begin(); for (Iterator i = begin(); i != end(); ++i, ++j) (*i) = (*j); return *this; } };
This example is from the ndarray project on Google Code and is not my own code.
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. To simply put, you can create a single function or single class to work with different data types using templates. C++ template is also known as generic functions or classes which is a very powerful feature in C++.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
5. Which keyword is used for the template? Explanation: C++ uses template reserved keyword for defining templates.
Here is an example where this->template
is required. It doesn't really match the OP's example though:
#include <iostream> template <class T> struct X { template <unsigned N> void alloc() {std::cout << "alloc<" << N << ">()\n";} }; template <class T> struct Y : public X<T> { void test() { this->template alloc<200>(); } }; int main() { Y<int> y; y.test(); }
In this example the this
is needed because otherwise alloc
would not be looked up in the base class because the base class is dependent on the template parameter T
. The template
is needed because otherwise the "<" which is intended to open the template parameter list containing 200, would otherwise indicate a less-than sign ([temp.names]/4).
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