我正在阅读 stl_construct.h 中的一些源代码,在大多数情况下,它在 <> 中有一些东西,我看到一些只有“ template<> ...
”的行。这是什么?
3 回答
这意味着接下来是模板专业化。
Guess, I completely misread the Q and answered something that was not being asked.
So here I answer the Q being asked:
It is an Explicit Specialization with an empty template argument list.
When you instantiate a template with a given set of template arguments the compiler generates a new definition based on those template arguments. But there is a facility to override this behavior of definition generation. Instead of compiler generating the definition We can specify the definition the compiler should use for a given set of template arguments. This is called explicit specialization.
The template<>
prefix indicates that the following template declaration takes no template parameters.
Explicit specialization can be applied to:
- Function or class template
- Member function of a class template
- Static data member of a class template
- Member class of a class template
- Member function template of a class template &
- Member class template of a class template
这是一个模板特化,其中所有模板参数都被完全指定,并且在<>
.
例如:
template<class A, class B> // base template
struct Something
{
// do something here
};
template<class A> // specialize for B = int
struct Something<A, int>
{
// do something different here
};
template<> // specialize both parameters
struct Something<double, int>
{
// do something here too
};