以下是代码:
template <typename T>
struct A
{
template <typename U>
struct B;
};
template <typename T> template <> // 0_o
struct A<T>::B<int> {};
我知道我不能这样做但是我更有兴趣逻辑地知道为什么我不能专门化嵌套模板成员而不专门封装类模板?
我感谢任何有关逻辑解释的帮助:)
Andrei Alexandrescu的回复:“没有特别的理由 - 这只是一种语言规则。”
答案 0 :(得分:1)
这是一个基于Xeo的例子的想法:首先,让我们有我们的候选主要模板:
template <typename T> struct Foo
{
template <typename U> struct Bar { /* ... */ };
/* ... */
};
现在假设我们想要专门化内部模板,假设:
template <typename T> template <> struct Foo<T>::Bar<bool> { /* ... */ }
// not actual C++!
但现在假设有Foo
的专业化:
template <> struct Foo<int>
{
template <typename U> struct Bar { /* ... */ };
};
template <> struct Foo<char>
{
template <typename U> U Bar() { }
};
现在如果你想使用Foo<S>::Bar<bool>
怎么办?当S = char
时,我们不能使用内部特化,因为它没有意义。但是如果我们不允许外部模板的所有特化的内部特化,那么Foo<int>::Bar<bool>
不是专门的,而Foo<float>::Bar<bool>
将专门化。因此,我们假设的内部专业化不适用于Foo<int>
,即使人们可能已经预料到应该这样做。
这不是一个真正的技术原因,它无法完成,而只是说明它将如何产生非常意外的行为。 (例如,假设int
的专门化稍后编写,现有代码依赖于内部专业化。)