非模板类中任何类型的C ++成员变量 [英] C++ member variable of any type in non-template class

查看:84
本文介绍了非模板类中任何类型的C ++成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在类中存储模板或自动变量而不使类作为模板?我试图存储一个指针到STL随机数生成器之一,但我不能找出任何方式来做,而不使整个类成为一个模板。这不是一个选项,因为将所有的东西在cpp中移动到h文件会导致一吨的循环头文件包括我不想处理。例如,它将是这样的:

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.

编辑:我知道我忘了提一些东西。我不能使用继承来指定RNG类型,因为我不知道什么是基数,除非有人知道什么基类是为STL使用的RNG。目前我使用std :: default_random_engine。

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.

推荐答案

如果你真的不想要模板,

I can think of two options if you really don't want templates:


  • 如果字面意思是任何类型,您可以使用 void * 。这不是非常类型安全,类的用户必须知道实际上是什么类型它做任何事情。

  • 如果你可以约束类型到一些基本接口/类,你可以使用指向该类型的指针,例如 IRandom * 。这一般似乎更有用/更有用。

  • If you literally mean any type, you can use 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.
  • If you can constrain the type to some base interface/class, you can use a pointer to that type instead, e.g. IRandom *. This seems a lot more useful/usable in general.

这篇关于非模板类中任何类型的C ++成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆