2

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

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 允许我做一些我不应该做的事情?

4

1 回答 1

0

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

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

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

现在,假设你想声明一个类型A<int>B<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 类中设置。

嵌套类模板

于 2012-04-23T18:51:22.833 回答