C++ 使用内部类型作为模板参数继承模板类
我可以这样做吗C++ 使用内部类型作为模板参数继承模板类,c++,templates,inheritance,C++,Templates,Inheritance,我可以这样做吗 template<class T> struct A { }; struct B : public A<B::X> { typedef string X; }; 我可以这样做吗 template<class T> struct A { }; struct B : public A<B::X> { typedef string X; }; 不,您不能,因为在您使用B::X时,类型B::X(或者类B)没有完全
template<class T> struct A {
};
struct B : public A<B::X> {
typedef string X;
};
我可以这样做吗
template<class T> struct A {
};
struct B : public A<B::X> {
typedef string X;
};
不,您不能,因为在您使用B::X
时,类型B::X
(或者类B
)没有完全声明
另一种方法是在a
类中添加typedef:
template<class T> struct A {
typedef T t_type;
};
不幸的是,不,这是不可能的。因为当您有
结构B:public A
时,类型别名B::X
还不存在
但是如果您知道X将是什么类型,为什么不使用实际的类型呢?像
struct B : public A<std::string>
{
typedef std::string X;
...
};
否,
B
此时是不完整的类型,不完整的类型不能在嵌套的名称说明符中使用
您可以将结构的定义移动到另一个类(EnumeratorBase
),然后执行以下操作:
template<class Iterator>
struct Enumerator
: private EnumeratorBase<Iterator>
, public iterator<input_iterator_tag, EnumeratorBase<Iterator>::value_type>
{
using typename EnumeratorBase<Iterator>::value_type;
};
模板
结构枚举器
:私有枚举数据库
,公共迭代器
{
使用typename EnumeratorBase::value\u type;
};
不幸的是,我不知道类型X
。也许我把简化的例子简化得太多了。正如您从较长的代码片段中观察到的,继承类迭代器的模板参数取决于继承类枚举器的模板参数迭代器,我真的无法修改A。我想@jrok的答案是正确的。在这种情况下,using关键字对我不起作用(错误:未知类型名称'value\u type'
),但另一个类型定义类型定义类型名称迭代器::value\u type value\u type派生类枚举器中的代码>。知道为什么在这里不能使用吗?@user3503380即使没有它也应该可以工作,g++和clang接受它,所以这可能是你的编译器的一个怪癖。不过呆在那里也没什么坏处。@user3503380不,等等,typename
当然是必需的。谢谢你指出这一点。
template<typename T = std::string>
struct B : public A<T>
{
typedef T X;
...
};
template<class Iterator>
struct Enumerator
: private EnumeratorBase<Iterator>
, public iterator<input_iterator_tag, EnumeratorBase<Iterator>::value_type>
{
using typename EnumeratorBase<Iterator>::value_type;
};