如何定义嵌套在类声明之外的模板化类中的模板化类的方法的专用化

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

本文关键字:专用 方法 声明 何定义 定义 嵌套      更新时间:2023-10-16

下面给了我几个编译错误:

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

如何在没有类声明中的定义的情况下执行此操作?

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()
{
}

编辑:

根据 14.7.3 §16,如果嵌套类模板的封闭类模板不是专用的,则嵌套类模板不能专用。但是,这让我想知道为什么嵌套类专用化在外部类声明中完全定义时会起作用,如下所示:

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

也许这只是VS2010允许我做一些我不应该做的事情?

问题在于,在使用类(或结构)时,您需要能够声明模板化类型。

因此,如果您有一个模板化的嵌套类,则需要在类本身中设置其类型,因为您将无法从"外部"执行此操作。
例如:

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

现在,假设您想声明一个带有 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

因此,您无法真正访问声明中的B
所以,B的类型必须在类A中设置。

嵌套类模板