Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ what does template<> mean?

Tags:

c++

templates

It's not a syntax I'm familiar with, but I saw it in another question, an example being:

template<> struct Allowed<std::string> { };

What does template<> actually mean, with no template type/parameter?

like image 734
Mr. Boy Avatar asked Feb 02 '11 09:02

Mr. Boy


People also ask

How many types of templates are there in C?

There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic.

Why do we use :: template template parameter?

8. Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.

Why template is used in C?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

What are template classes?

Template class. is an instance of a class template. A template definition is identical to any valid class definition that the template might generate, except for the following: The class template definition is preceded by template< template-parameter-list >


3 Answers

It is a template specialization. The typical case would be partial specialization:

#include <iostream>

template<class T1, class T2>
struct foo
{
  void doStuff() { std::cout << "generic foo "; }
};

template<class T1>
struct foo<T1, int>
{
 void doStuff() { std::cout << "specific foo with T2=int"; }
};

As you can see, the specialization removes one element from the template parameters and explicitly states a type instead of the removed one. That means if there is only one template type, the <> just become empty:

template<class T1>
struct bar
{
  void doStuff() { std::cout << "generic bar"; }
};

template<>
struct bar<int>
{
 void doStuff() { std::cout << "specific bar with T1=int"; }
};
like image 172
Mephane Avatar answered Oct 28 '22 16:10

Mephane


It's a specialization. template<> means that the specialization itself is not templated- i.e., it is an explicit specialization, not a partial specialization.

like image 37
Puppy Avatar answered Oct 28 '22 16:10

Puppy


You might just say it is just the required syntax.

The normal syntax would be template< typename T > struct Allowed;

Because we know that in this case T is std::string there is nothing to put inside the angled brackets but the word template and the angled brackets are still required because writing struct Allowed<std::string> on its own would not imply that you are specializing the template but simply that you are instantiating one with std::string as the type. (The word "struct" is not necessary to do that but is still permitted).

like image 11
CashCow Avatar answered Oct 28 '22 16:10

CashCow