如何定义嵌套在类声明之外的模板化类中的模板化类的方法的专用化
How can you define a specialization of a method of a templated class nested in a templated class outside of the class declaration?
下面给了我几个编译错误:
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中设置。
嵌套类模板
相关文章:
- 检查子类型时的专用方法模板
- 部分方法专用化
- 基于枚举参数调用专用模板方法
- 类中一种方法的部分专用化
- 从非模板类调用专用模板方法
- 使用类指针重载C++命名空间函数模板专用化替代方法?
- 没有针对完全专用模板类的外联虚拟方法定义
- 从部分专用模板方法调用模板非静态方法
- 添加具有模板专用化的方法
- 常量字符*的模板方法专用化
- 两种专用方法中的相同代码
- C++隐式/显式模板方法专用化问题
- C++复杂类型的单一方法的模板专用化
- enable_if在类声明之外实现的方法专用化
- 模板化类和模板化方法的模板专用化语法
- 获取非专用标准::矢量容器的标准方法<bool>
- 一种安全、符合标准的方法,使类模板专用化仅在实例化时才无法使用"static_assert"进行编译
- boost:enable_if 在模板化类中定义专用方法
- 模板类的专用方法
- 从专用方法捕获异常