代码:
template<>
std::map<int, std::vector<std::string> > Storage<int>::things = {
{ 1, {"FOO", "foo"} },
{ 2, {"BAR", "bar"} },
{ 3, {"ZAR", "zar"} }
};
不是类模板Storage的特化,而是a static data member of a class template的特化。
模板类的成员可以特化(只要没有非静态数据成员)。也就是说,可以将整个模板类特化为一个整体,如下所示:
template<class T>
struct A{
struct B{
using type = T;
};
void g();
};
template<>
struct A<void>{}; //specialize the entire class.
或者只特化类模板的成员:
//Specialization of B for A<int>
template<>
struct A<int>::B{
static int f();
};
上述成员特化等价于模板类特化:
template<>
struct A<int>{
struct B{ //come from the member specialization definition
static int f();
};
void g(); //come from unspecialized A definition.
};
因此,如果您尝试编译,您可能会观察到这一点:
A<char>::B::type x = `a`;
A<double>::B::type y = `b`;
A<int>::B::type err; //compilation error
int z = A<int>::B::f(); //ok.
A<void>::B o; //compilation error
auto w = A<void>::f(); //compilation error