使用(非类型)枚举参数定义内部类成员函数模板

时间:2013-02-08 16:09:14

标签: c++ templates inner-classes specialization non-type

我在定义和专门化内部类update()的成员函数Outer<T1>::Inner时遇到困难,该函数在非类型(枚举)参数上被模板化。

#include <cstdlib>

template<typename T1>
struct Outer
{
    struct Inner
    {
        enum Type{ A , B , C };

        template<Type T2>
        void update();
    };
};

// Definition
template<typename T1>
template<Outer<T1>::Inner::Type T2>
void Outer<T1>::Inner::update()
{
}

// Specialization
template<typename T1>
template<Outer<T1>::Inner::A >
void Outer<T1>::Inner::update()
{
}

int main()
{
    return EXIT_SUCCESS;
}

我在GCC 4.5.3中收到以下错误消息

prog.cpp:17:28: error: ‘Outer::Inner::Type’ is not a type
prog.cpp:18:6: error: prototype for ‘void Outer<T1>::Inner::update()’ does not match any in class ‘Outer<T1>::Inner’
prog.cpp:11:15: error: candidate is: template<class T1> template<Outer<T1>::Inner::Type T2> void Outer<T1>::Inner::update()
prog.cpp:24:28: error: ‘Outer::Inner::A’ is not a type
prog.cpp:25:6: error: prototype for ‘void Outer<T1>::Inner::update()’ does not match any in class ‘Outer<T1>::Inner’
prog.cpp:11:15: error: candidate is: template<class T1> template<Outer<T1>::Inner::Type T2> void Outer<T1>::Inner::update()

BTW,与GCC不同,Visual Studio 2008无法编译以下内容

template<typename T1>
struct Outer
{
    struct Inner
    {
        enum Type{ A , B , C };

        template<Type T2>
        struct Deep;
    };
};

template<typename T1>
template<typename Outer<T1>::Inner::Type T2>
struct Outer<T1>::Inner::Deep
{
};

1 个答案:

答案 0 :(得分:5)

首先,您在typename之前错过了Outer<T1>::Inner::Type。您必须拥有它,即使在template类型列表中也是如此,因为Type是一种依赖类型。

其次,你的专业化语法是错误的(类型在括号前面的函数名之后<>,而不是template<>),但即使它是正确的,它也不合法。根据关于显式模板专业化的不幸规则,您必须在完全专门化Outer之前专门化外部模板update