Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an empty template argument <> while creating an object?

Here is some valid syntax:

std::uniform_real_distribution<> randomizer(0, 100);

How does it work, does it automatically deduce the object template? Why is it necessary to write <> at the end of the type? Can I not remove the <> and it will be the same?

like image 379
Narek Avatar asked Jul 14 '15 11:07

Narek


2 Answers

Typically this can be used and works when the first and succeeding, or only, parameter has a default template argument (type or value if it is an integral). An additional case is when there is a template argument pack and it is empty.

The <> is still needed to identify it as a template type.

In this case the type is declared as;

template <class RealType = double>
class uniform_real_distribution;

Hence the default RealType for the template class uniform_real_distribution is double. It amounts to std::uniform_real_distribution<double>.


With reference to the C++ WD n4527, §14.3/4 (Template arguments)

When template argument packs or default template-arguments are used, a template-argument list can be empty. In that case the empty <> brackets shall still be used as the template-argument-list. [ Example:

template<class T = char> class String;
String<>* p; // OK: String<char>
String* q;   // syntax error

template<class ... Elements> class Tuple;
Tuple<>* t; // OK: Elements is empty
Tuple* u;   // syntax error

- end example ]

like image 197
Niall Avatar answered Dec 02 '22 05:12

Niall


The class has the following declaration

template<class RealType = double>
class uniform_real_distribution;

As you can see it has default template argument of type double

So this declaration

std::uniform_real_distribution<> randomizer(0, 100);

is equivalent to

std::uniform_real_distribution<double> randomizer(0, 100);
like image 38
Vlad from Moscow Avatar answered Dec 02 '22 04:12

Vlad from Moscow