Criss
Criss

Reputation: 621

Template specialization for type concretized by template parameter

First of all I'm very sorry for the question title, but it's very hard to describe. What of those two below is valid syntax if I want to specialized Resolve for all instantiation of A?
1)

template<uint32_t I> struct A {};

template<typename> struct Resolve;

template<uint32_t I>
struct Resolve<A<I>>
{
    void f() { printf("im here!\n"); }  
};

2)

template<uint32_t I> struct A {};

template<typename> struct Resolve;

template<>
template<uint32_t I>
struct Resolve<A<I>>
{
    void f() { printf("im here!\n"); }  
};

Or is template<> optional? There's two different answers on SO: here and here.
Also please provide quotation of the standard if possible.

Option 2) doesn't compile on MSVC, but does compile at least on some versions of GCC.

Upvotes: 0

Views: 219

Answers (1)

Barry
Barry

Reputation: 304122

This is correct:

template <uint32_t I>
struct Resolve<A<I>>
{ };

The syntax template <> is used to introduce an explicit specialization (of a class template, function template, whatever) (see [temp.spec]/3 and [temp.expl.spec]/1). But we're trying to do a partial specialization. A partial specialization still needs to introduce template parameters, an explicit specialization does not.

On the other hand, if we were trying to specialize a member of an explicit specialization, then we'd use template <>. For instance:

template <class T>
struct A {
    template <class T2> struct B { }; // #1
};

template <>         // for A
template <class T2> // for B
struct A<int>::B<T2> { }; // #2

A<char>::B<int> x; // #1
A<int>::B<char> y; // #2

Upvotes: 1

Related Questions