开发者

What is the "template" keyword doing before "class" keyword?

Just some code sample [Not a real life example]

// at file scope

template <ty开发者_JAVA百科pename T, typename U>
struct demo{};  
template class demo<int, int>; // is the template keyword optional here?

Is the template keyword optional in line 3? I haven't (often) seen this usage of the template keyword before. Which part of the standard says allows this?

EDIT

I think g++ has a bug then.

template <typename T, typename U>
struct demo{};  
class demo<int, int>; // template keyword omitted

compiles on g++ (4.5.1) whereas fails on Comeau

"ComeauTest.c", line 5: error: specializing class "demo<int, int>" without
          "template<>" syntax is nonstandard
      class demo<int, int>; 


That's an explicit instantiation.

Typically when you use a template, the compiler generates what you need, as you need it. To provide essential specializations of a class template in a static or dynamic library, however, you want to generate all the members, all at once, to make sure they are delivered to the user.

For example, most implementations of the C++ standard library explicitly specialize std::ostream<char,char_traits<char> >, because otherwise applications would end up including repetitive copies of various operations on cout.

This syntax is identical with explicit instantiation. C++03 §14.7.2/2:

The syntax for explicit instantiation is:

explicit-instantiation:

template declaration

Edit:

It looks like you stumbled on obsolete syntax for specializing, not explicitly instantiating, a class template. Comeau is warning you that it took the template-id declaration as a forward declaration of an explicit specialization. Presumably GCC is doing the same. It is unlikely that you are obtaining explicit instantiation in that case. Also, it is undefined behavior to use an explicit template specialization before it is defined. (Fundamentally, the implicit specialization causes a violation of the one-definition rule.)

Note that GCC also supports extern template instantiations:

extern template declaration

In the case of an extern function instantiation, I would not be surprised if template were optional. But, neither would I be surprised to find it is required, nor omit it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜