嵌套类模板特化 [英] Nested class template specialization
问题描述
一类:
template<typename C, typename T>
class A
{
template <typename U>
class Nested{};
Nested<T> n;
};
而且我想专门化Nested
.这是我尝试过的:
And I want to specialize Nested
. Here what I tried:
template<typename C, typename T>
class A
{
template <typename U>
class Nested{};
template <>
class Nested<int>{}; // by my logic this should work by I have a compilation error "explicit specialization in non-namespace scope 'class A<C, T>'"
Nested<T> n;
};
我的下一次尝试:
template<typename C, typename T>
class A
{
template <typename U>
class Nested{};
Nested<T> n;
};
template<>
A<>::Nested<int>{}; // What is the correct syntax to do it here? Now I have an error "wrong number of template arguments (0, should be 2)"
在stackoverflow上我找到了一个解决方案:
Here on stackoverflow I found a solution:
template<typename C, typename T>
class A
{
template <typename U, bool Dummy = true>
class Nested{}; // why need of this Dummy??
template <bool Dummy>
class Nested<int, Dummy>{}; // why need to provide an argument??
Nested<T> n;
};
它完美地工作,但我不明白如何.为什么要提供一个虚拟模板参数?为什么我不能使用原始专业化template<>class Nested
或 template<>class Nested
?
It perfectly works, but I can't understand how. Why to provide a dummy template argument? Why can't I use raw specialization template<> class Nested<int, true>{}
or template<> class Nested<int>{}
?
推荐答案
禁止在类范围内创建显式特化:
It's forbidden to create explicit specialization in class-scope:
一个显式的特化应该在一个命名空间中声明专用模板.
An explicit specialization shall be declared in a namespace enclosing the specialized template.
但不禁止创建偏特化:
可以声明或重新声明类模板部分特化在可以定义其定义的任何命名空间范围内(14.5.1和 14.5.2).
A class template partial specialization may be declared or redeclared in any namespace scope in which its definition may be defined (14.5.1 and 14.5.2).
这个
template <bool Dummy>
class Nested<int, Dummy>{}; // why need to provide an argument??
是部分特化,允许在类范围内创建这样的特化.您也不能在非专门化的外部类中完全专门化嵌套类.你可以这样做:
is partial specialization and it's allowed to create such specialization in class-scope. You also cannot fully specialize nested class, in not-specialized outer class. You can do this:
template<>
template<>
class A<int, double>::Nested<int>
{
};
但你做不到
template<typename C, typename T>
template<>
class A<C, T>::Nested<int>
{
};
这篇关于嵌套类模板特化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!