在C ++中,模板<>是什么?意思?

时间:2011-02-02 09:42:09

标签: c++ templates

这不是我熟悉的语法,但我在another question中看到了它,例如:

template<> struct Allowed<std::string> { };

template<>实际意味着什么,没有模板类型/参数?

3 个答案:

答案 0 :(得分:20)

这是一个模板专业化。典型案例是部分专业化:

#include <iostream>

template<class T1, class T2> struct foo
{
  void doStuff() { std::cout << "generic foo "; }
};

template<class T1>
struct foo<T1, int>
{
 void doStuff() { std::cout << "specific foo with T2=int"; }
};

如您所见,专门化从模板参数中删除了一个元素,并明确指出了一个类型而不是删除的类型。这意味着如果只有一种模板类型,<>就会变空:

template<class T1> struct bar
{
  void doStuff() { std::cout << "generic bar"; }
};

template<>
struct bar<int>
{
 void doStuff() { std::cout << "specific bar with T1=int"; }
};

答案 1 :(得分:17)

这是一种专业化。 template<>意味着专业化本身不是模板化的 - 即,它是一种明确的专业化,而不是部分专业化。

答案 2 :(得分:5)

您可能只是说这只是必需的语法。

正常语法为template< typename T > struct Allowed;

因为我们知道在这种情况下T是std :: string,所以没有任何内容放在有角度的括号内,但是仍然需要单词模板和有角度的括号,因为写作 struct Allowed<std::string>本身并不意味着你专门用于模板,而仅仅是你用std :: string作为类型来实例化。 (“struct”这个词不是必须这样做的,但仍然允许)。

相关问题