c++templatesc++11

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?


Solution

  • 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 ]