为什么我不能专门化嵌套的模板成员,而不专门封装类模板? [英] Why can't I specialize the nested template member without specializing enclosing class template first?

查看:140
本文介绍了为什么我不能专门化嵌套的模板成员,而不专门封装类模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是代码:

template <typename T>
struct A
   {
   template <typename U>
   struct B;
   };
template <typename T> template <> // 0_o
struct A<T>::B<int> {};

我知道我不能这样做,但我更感兴趣知道逻辑为什么不能

I know I can't do this but I'm more interested to know logically Why can't I specialize the nested template member without specializing enclosing class template first?

我赞赏任何有关逻辑解释的帮助:)

I appreciate any help with logical explanation :)

Andrei Alexandrescu的回答:没有特别的原因 - 这只是一个语言规则。

Andrei Alexandrescu's reply : "There's no particular reason - it's just a language rule."

推荐答案

这里有一个基于Xeo例子的想法:首先,让我们有我们的候选主模板:

Here's an idea based on Xeo's example: First, let's have our candidate primary template:

template <typename T> struct Foo
{
    template <typename U> struct Bar { /* ... */ };
    /* ... */
};

现在假设我们想特殊化内部模板,假设:

Now suppose we want to specialize the inner template, hypothetically:

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& bool> 吗?当 S = char 时,我们不能使用内部专门化,因为它没有意义。但是如果我们不允许外部模板的所有专业化的内部专门化,则 Foo > Foo< float> :: Bar< bool> 所以我们假设的内部特化不适用于 Foo ,即使可能预期应该这样。

Now what if you want to use Foo<S>::Bar<bool>? When S = char, we cannot use the inner specialization, because it makes no sense. But if we disallow the inner specialization for all specializations of the outer template, then Foo<int>::Bar<bool> isn't specialized, while Foo<float>::Bar<bool> will be specialized. So our hypothetical inner specialization does not apply to Foo<int>, even though one might have expected that it should.

这不是一个真正的技术原因,它不能做,但只是一个说明如何会有非常意想不到的行为。 (例如,假设稍后编写 int 的专业化,现有代码依赖于内部专业化。)

This isn't a real technical reason that it can't be done, but just an illustration how it would have very unexpected behaviour. (For instance, imagine the specialization for int was written later, and existing code depended on the inner specialization.)

这篇关于为什么我不能专门化嵌套的模板成员,而不专门封装类模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆