[英]Can I use a class level typedef as template argument for the base class?
Assume a templated base class: 假设一个模板化的基类:
template<typename T>class BaseClass;
In other classes I want to inherit from this, where T
is a rather complicated type, so I would like to use a typedef
. 在其他类中我想继承这个,其中
T
是一个相当复杂的类型,所以我想使用typedef
。 Because I do not want to pollute the namespace I want to have the typedef
inside the class definition: 因为我不想污染命名空间,所以我希望在类定义中包含
typedef
:
class ChildClass : public BaseClass<MyVeryVeryVeryComplicatedType> {
typedef MyVeryVeryComplicatedType LocalType;
...
}
Now of course I cannot yet use LocalType
as the template argument for BaseClass
and have to write the complicated definition ( MyVeryVeryComplicatedType
) twice. 现在我当然还不能使用
LocalType
作为BaseClass
的模板参数,并且必须编写两次复杂的定义( MyVeryVeryComplicatedType
)。 (So the answer to the title question is 'No', I guess.) (所以标题问题的答案是'不',我猜。)
Question: Is there any way to only have the definition only once but still only defined inside the class (or in a similar way that limits the scope of LocalType
)? 问题:有没有办法只定义一次定义,但仍然只在类中定义(或以限制
LocalType
范围的类似方式)?
Note: I thought about using a macro, but noticed that the result would be the same (or even worse) as having the typedef
before the class definition. 注意:我考虑过使用宏,但注意到结果与类定义之前的
typedef
相同(甚至更糟)。
Edit: For clarification: I have a base class because I want to want to have several different children which share some functionality. 编辑:澄清:我有一个基类,因为我想要有几个不同的孩子共享一些功能。 The shared parts only need to know that there is some type
T
. 共享部分只需要知道有一些类型
T
Since the details of the types used in the child classes have nothing to do with the shared functionalities I think that the base class should not know of these details (in practice, I would have to put a lot of #include
statements into the base class to be able to define the typedef
s for all child classes). 由于子类中使用的类型的细节与共享功能无关,我认为基类不应该知道这些细节(实际上,我必须将很多
#include
语句放入基类中能够为所有子类定义typedef
)。 Each child class has a rather different MyVeryVeryVeryComplicatedType
. 每个子类都有一个相当不同的
MyVeryVeryVeryComplicatedType
。
Just use a little helper namespace: 只需使用一个小助手命名空间:
namespace ChildClassNamespace {
typedef MyVeryVeryComplicatedType LocalType;
class ChildClass : public BaseClass<LocalType> { /* ... */ };
}
using ChildClassNamespace::ChildClass;
No. Put the typedef
in the enclosing namespace. 不。将
typedef
放在封闭的命名空间中。
That makes the most sense anyway , since you're using it in two of that namespace's types ( ChildClass
and BaseClass<LocalType>
). 无论如何 ,这是最有意义的 ,因为你在两个命名空间的类型(
ChildClass
和BaseClass<LocalType>
)中使用它。
You could define it in the base class: 您可以在基类中定义它:
template <typename T> class BaseClass {
protected:
typedef T LocalType;
// whatever else
};
class ChildClass : public BaseClass<MyVeryVeryVeryComplicatedType> {
// LocalType is usable here, and aliases MyVeryVeryVeryComplicatedType
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.