0

以下代码编译成功,我不明白为什么:

#include <stdio.h>
#include <vector>
#include <iostream>

// Template definition
template <typename T1, typename T2> class stack
{
};

// Template specialization
template <> class stack <float, float>
{
};

int main ()
{
  stack <char, char> objStack;
  return 0;
}    

部分特化不是意味着我们可以将类用于某些特定的数据类型,我们在特化中指定了这些类型吗?

这里没有专门的char类,如果要编译任何类型的数据类型,那么专门化的目的是什么?

4

2 回答 2

2

模板专业化意味着采用通用模板并添加将用于一组特殊类型的类型或函数。部分特化是指您的模板类型或函数具有多个参数,并且您没有在特化中指定所有参数。

在您的示例中,此功能是通用模板。

// Template definition
template <typename T1, typename T2> class stack
{
};

它将为您提供的任何类型实例化,除非您提供两个浮点数。如果您将两个浮点数作为参数,则此模板

// Template specialization
template <> class stack <float, float>
{
};

将被实例化。

于 2011-04-02T06:02:46.103 回答
2

模板专业化适用于您想要为特定模板参数做一些特别不同的事情。编译器将实例化原始模板中未指定的任何内容。

当您想要特定数据类型的不同行为时,这很有用,但也可用于更复杂的模式匹配,例如更改指针类型或const类型的行为:

template <typename T>
struct is_pointer { static bool value = false; };

template <typename T>
struct is_pointer<T*> { static bool value = true; };

template <typename T>
struct is_const { static bool value = false; };

template <typename T>
struct is_const<const T>  { static bool value = true; };

// later, try this:
assert(is_pointer<int*>::value == true);
assert(is_pointer<int>::value == false);

So, long story short: don't bother specifying your template unless you've got something special to do with a certain parameter, that you can't generalize into the base-template. Template specialization is just a rather hardcore form of pattern-matching which can be used for both good and evil.

于 2011-04-02T06:04:09.647 回答