这是代码:
template <typename T>
struct A
{
template <typename U>
struct B;
};
template <typename T> template <> // 0_o
struct A<T>::B<int> {};
Run Code Online (Sandbox Code Playgroud)
我知道我不能这样做,但我更有兴趣知道逻辑上为什么我不能专门化嵌套模板成员而不专门封装类模板?
我很感激任何有关逻辑解释的帮助:)
Andrei Alexandrescu的回答:"没有特别的理由 - 这只是一种语言规则."
这是一个基于 Xeo 示例的想法:首先,让我们拥有候选主模板:
template <typename T> struct Foo
{
template <typename U> struct Bar { /* ... */ };
/* ... */
};
Run Code Online (Sandbox Code Playgroud)
现在假设我们想要专门化内部模板:
template <typename T> template <> struct Foo<T>::Bar<bool> { /* ... */ }
// not actual C++!
Run Code Online (Sandbox Code Playgroud)
但现在假设有以下专业Foo:
template <> struct Foo<int>
{
template <typename U> struct Bar { /* ... */ };
};
template <> struct Foo<char>
{
template <typename U> U Bar() { }
};
Run Code Online (Sandbox Code Playgroud)
现在如果你想使用怎么办Foo<S>::Bar<bool>?当 时S = char,我们不能使用内部特化,因为它没有意义。但是,如果我们不允许外部模板的所有专业化的内部专业化,则Foo<int>::Bar<bool>不会专业化,而Foo<float>::Bar<bool> 将专业化。因此,我们假设的内部专业化不适用于Foo<int>,尽管人们可能期望它应该如此。
这并不是无法完成的真正技术原因,而只是说明它会如何产生非常意外的行为。(例如,假设 for 的专业化int是后来编写的,并且现有代码依赖于内部专业化。)
| 归档时间: |
|
| 查看次数: |
349 次 |
| 最近记录: |