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

后端 未结 1 1443
悲哀的现实
悲哀的现实 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 <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++!
    

    But now suppose there are specializations of Foo:

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

    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.

    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)
提交回复
热议问题