Benjamin Bannier
Benjamin Bannier

Reputation: 58774

Syntax for explicit template specializations

The following is accepted by both gcc-4.9.2 and clang-3.8 when compiling as C++98 or C++11,

#include <cstdio>

template <typename T> void f(T) { printf("T\n"); }
template <> void f<int>(int) { printf("int\n"); }    // explicit specialization
template <> void f<>(double) { printf("double\n"); } // explicit specialization -- 14.7.2(7)
template <> void f(float) { printf("float\n"); }     // HERE

int main() {
  f(1L);    // T
  f(10);    // int
  f(10.0);  // double
  f(10.0F); // float
}

I see that in the C++11 standard §14.7.2(7) deducing trailing template arguments in explicit template specializations is permitted, but I cannot find whether or how the terser form marked HERE is allowed.

Are these compilers conformant or is this some extension?

Upvotes: 4

Views: 599

Answers (1)

NathanOliver
NathanOliver

Reputation: 181047

C++14 standard §14.7(3) has

An explicit specialization may be declared for a function template, a class template, a member of a class template or a member template. An explicit specialization declaration is introduced by template<>. In an explicit specialization declaration for a class template, a member of a class template or a class member template, the name of the class that is explicitly specialized shall be a simple-template-id. In the explicit specialization declaration for a function template or a member function template, the name of the function or member function explicitly specialized may be a template-id.

And then demonstrates

template<class U> void g(U) { }
template<> void g(char) { }       //specialize for U == char
                                  // U is deduced from the parameter type

And then we have §14.7.3(10)

A trailing template-argument can be left unspecified in the template-id naming an explicit function template specialization provided it can be deduced from the function argument type. [ Example:

template<class T> class Array { / ... / };
template<class T> void sort(Array<T>& v);

// explicit specialization for sort(Array<int>&)
// with deduced template-argument of type int
template<> void sort(Array<int>&);

—end example ]

Upvotes: 3

Related Questions