简体   繁体   中英

Is `template<>` optional when specializing a class template using another class template?

I was trying to specialize a class template with another, as in the example below, and I noticed that this compiles and runs (at least on ideone, which is: gcc 4.3.4) whether the commented out line is commented out or not.

#include <iostream>
template <typename F>
struct foo{
  typedef F value_type;
};

template <typename G>
struct bar{};

//template<>  <- works if commented out or not
template <typename F>
struct bar<foo<F> >
{
  typename foo<F>::value_type val;
};

int main(void)
{
  typedef foo<int> F;
  typedef bar<F> B;
  B b;
  b.val = 10;
  std::cout << b.val << std::endl;
  return 0;
};

So my question is, is it really optional? I was under the impression that for such specialization the template<> line is required..

This

template<>
template <typename F>
struct bar<foo<F> >;

should be a syntax error, me thinks.

That line should not be there.

When doing full specialization, there is template<> and it's mandatory. When doing partial specialization, you put the parameters of the partial specialization to those angle brackets and there is no additional template keyword.

So full specialization is:

template <>
struct bar<qyzzy>

and partial specialization is:

template <typename F>
struct bar<foo<F> >

Each has exactly one template keyword and two pairs of angle brackets.

The line with template <> should be commented out. Otherwise it should be an error. Bar is a namespace-level template, so in order to specialize it you just write

template <parameters if any>
class bar <arguments>
{
};

I have no idea why gcc accepts when you uncomment the line. I can assure you it most certainly should not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM