考虑以下:
template <typename T>
class Base {
public:
template <typename U>
class Nested { };
};
template <typename T>
class Derived : public Base<T> {
public:
//How do we typedef of redefine Base<T>::Nested?
using Base<T>::Nested; //This does not work
using Base<T>::template<typename U> Nested; //Cannot do this either
typedef typename Base<T>::template<typename U> Nested Nested; //Nope..
//now we want to use the Nested class here
template <typename U>
Class NestedDerived : public Nested { };
//or like this:
Nested<int> nestedVar; // obviously does not work
};
如何在Derived类中使用模板Nested类?在当前版本的 C++ 标准中可以做到这一点吗?
实际上using
正如所宣传的那样,它只是没有消除模板中的从属名称问题,并且当前无法直接为模板添加别名(将是已在 C++0x 中修复 http://www2.research.att.com/~bs/C++0xFAQ.html#template-alias):
template <class T>
struct Base {
template <class U> struct Nested {};
};
template <class T>
struct Derived : Base<T> {
using Base<T>::Nested;
// need to prefix Nested with template because
// it is a dependent template:
struct X : Base<T>::template Nested<int> {};
// same here:
template<class U>
struct Y : Base<T>::template Nested<U> {};
// data member, typename is needed here:
typename Base<T>::template Nested<int> data;
};
void f() {
Derived<int>::Nested<int> n; // works fine outside
}
还有另一种可能gotcha使用时Derived<T>::Nested
在模板中,但这又是一个从属名称问题,与继承无关:
template<class T>
void g() {
// Nested is a dependent type and a dependent template, thus
// we need 'typename' and 'template':
typedef typename Derived<T>::template Nested<int> NestedInt;
}
请记住,依赖于模板参数的名称必须是
- 前缀为
typename
如果它是依赖类型:typename A<T>::B
- 直接加上前缀
template
如果它是一个依赖模板:A<T>::template f<int>()
- 两者如果两者都:
typename A<T>::template B<int>
-
typename
在基类列表中是非法的:template<class T> struct A : B<T>, C<T>::template D<int> {};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)