[英]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()
{
}
According to 14.7.3 §16 a nested class template cannot be specialized if it's enclosing class template is not also specialized. 根据14.7.3§16,如果嵌套的类模板也不是专用的,则它不能是专用的。 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? 也许这只是VS2010,允许我做一些我不应该做的事情?
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 ? 现在,假设您要使用
B<int>
声明一个类型为A<int>
的变量...您将如何做?
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. 因此,您不能真正在声明中访问
B
So, B
's type has to be set within the class A. 因此,必须在类A中设置
B
的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.