简体   繁体   中英

How can you define a specialization of a method of a templated class nested in a templated class outside of the class declaration?

The following gives me a couple compile errors:

error C2995: 'void A<T>::B<Q>::func(void)' : function template has already been defined
error C3855: 'A<T>::B<Q>': template parameter 'Q' is incompatible with the declaration

How can I do this without having the definitions in the class declaration?

template<typename T>
struct A
{
    template<typename Q>
    struct B
    {
        void func();
    };
};

template<typename T>
template<typename Q>
void A<T>::B<Q>::func()
{
}

template<typename T>
template<>
void A<T>::B<int>::func()
{
}

Edit:

According to 14.7.3 §16 a nested class template cannot be specialized if it's enclosing class template is not also specialized. However, that makes me wonder why the nested class specialization works when it's completely defined within the outer class declaration like so:

template<typename T>
struct A
{
    template<typename Q>
    struct B
    {
        void func(){}
    };

    template<>
    struct B<int>
    {
        void func(){}
    };  
};

Perhaps this is just VS2010 allowing me to do something I shouldn't be able to do?

The problem is in the fact that you need to be able to declare the templated type when you use the class (or struct).

So, if you have a templated nested class, its type would need to be set in the class itself, because you won't be able to do that from the "outside".
for example:

template<typename T>
struct A
{
    template<typename Q>
    struct B
    {
        void func(){}
    };
};

Now, lets say you'd want to declare a variable of type A<int> with B<int> ... how would you do it ?

A<int>::B<int> a; //this syntactically would mean a is of type B<int>
A<int,int> a; //this would mean A is a templated class with 2 templated types

So, you can't really access B in the declaration.
So, B 's type has to be set within the class A.

Nested Class Templates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM