C++非模板类中任意类型的成员变量
有没有某种方法可以在类中存储模板或自动变量而不使该类成为模板?我试图存储一个指向 STL 随机数生成器之一的指针,但我无法找出任何方法来做到这一点,而不将整个类放入模板中。这不是一个选项,因为将 cpp 中的所有内容移动到 h 文件会导致大量我不想处理的循环头文件。例如,它会是这样的:
class tSomeClass
{
public:
template<typename RNG>
tSomeClass(RNG * rng) : fRNG(rng) { }
private:
RNG * fRNG; // How do I get this working???
};
到目前为止,我想出的所有内容总是最终需要将整个类作为模板,所以我很困惑。
编辑:我知道我忘了提一件事。我无法使用继承来指定 RNG 类型,因为我不知道基类是什么,除非有人知道 STL 使用的 RNG 的基类是什么。目前我正在使用 std::default_random_engine。
Is there some way to store a template or auto variable in a class without making the class a template? I'm trying to store a pointer to one of the STL random number generators that but I can't figure out any way to do it without making the entire class into a template. This is not an option since moving all of the stuff in the cpp to h file would cause a ton of cyclic header file includes that I don't want to deal with. So for example it would be something like this:
class tSomeClass
{
public:
template<typename RNG>
tSomeClass(RNG * rng) : fRNG(rng) { }
private:
RNG * fRNG; // How do I get this working???
};
So far everything I've come up with always ends up with needing to have the entire class as a template so I'm stumped.
EDIT: I knew I forgot to mention something. I can't use inheritance to specify the RNG type since I have no idea what the base is, unless someone knows what the base class is for the RNGs being used by STL. Currently I'm using std::default_random_engine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您确实不需要模板,我可以想到两个选择:
void *
。这不是非常类型安全的,类的用户必须确切地知道它实际上是什么类型才能用它做任何事情。IRandom *
。一般来说,这似乎更有用/可用。I can think of two options if you really don't want templates:
void *
. This is not very type safe, and the users of the class would have to know exactly what type it actually is to do anything with it.IRandom *
. This seems a lot more useful/usable in general.安全且正确的方法是定义一个描述接口的类并在实际实现中继承它。
例子:
The safe and correct way is to define a class describing the interface and inherit it on actual implementations.
Example:
C 方法是使用通用指针 (
void*
),但是由于这是 C++,因此只需利用继承和动态绑定,即:或者如果这就是您的所有随机数,甚至可以使用函数指针发电机组成。
The C way is to use a general pointer (
void*
), however since this is C++ just take advantage of inheritance and dynamic binding, ie:Or even a function pointer will do if that's all your random number generators consist of.