Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a call to 'this->template [somename]' do?

Tags:

c++

templates

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.

like image 365
Phillip Cloud Avatar asked Apr 03 '11 23:04

Phillip Cloud


People also ask

What does template do in C++?

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++.

What is the purpose of template parameter?

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.

Which keyword is used to define template?

5. Which keyword is used for the template? Explanation: C++ uses template reserved keyword for defining templates.


1 Answers

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).

like image 68
Howard Hinnant Avatar answered Oct 03 '22 01:10

Howard Hinnant