Why can't I specialize the nested template member without specializing enclosing class template first?

后端 未结 1 1452
悲哀的现实
悲哀的现实 2021-01-08 01:16

Here is the code :

template 
struct A
   {
   template 
   struct B;
   };
template  template <> /         


        
1条回答
  •  粉色の甜心
    2021-01-08 01:52

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

    template  struct Foo
    {
        template  struct Bar { /* ... */ };
        /* ... */
    };
    

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

    template  template <> struct Foo::Bar { /* ... */ }
    // not actual C++!
    

    But now suppose there are specializations of Foo:

    template <> struct Foo
    {
        template  struct Bar { /* ... */ };
    };
    template <> struct Foo
    {
        template  U Bar() { }
    };
    

    Now what if you want to use Foo::Bar? 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::Bar isn't specialized, while Foo::Bar will be specialized. So our hypothetical inner specialization does not apply to Foo, even though one might have expected that it should.

    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.)

    0 讨论(0)
提交回复
热议问题