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

标签 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()

顺便说一句,与 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
{
};

最佳答案

首先,您缺少一个 typename之前 Outer<T1>::Inner::Type .你必须拥有它,即使在 template输入列表,因为 Type是依赖类型。

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

关于c++ - 使用(非类型)枚举参数定义内部类成员函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14776699/

相关文章:

c++ - 如果默认可构造,则默认参数

function - 如何在 Kotlin 中初始化嵌套数据类?

c++ - 如何访问 C++ 中的私有(private)嵌套类?

c++ - Libcurl 返回损坏的数据

c++ - 如何通过子类型列表创建指针 vector ?

c++ - 这个电话去哪儿了?

c++ - 如果我们在 C++ 中重载构造函数,默认构造函数是否仍然存在?

c++ - 对类模板成员函数的 undefined reference

C++11 模板函数别名与包装器

c++ - 嵌套类的嵌套类的访问权限