简体   繁体   中英

C++ member variable of any type in non-template class

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.

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

  • 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, eg 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:

class RNG {
    public:
        virtual int get(void) = 0;
}

The C way is to use a general pointer ( void* ), however since this is C++ just take advantage of inheritance and dynamic binding, ie:

class RNG /* random number generator interface/base class */
{
   public:
      virtual int randomize(void) = 0; 
};

class RandomA : public RNG /* one implementation of a random num generator */
{
   public:
      int randomize() { return 4; }
};

class RandomB : public RNG /* another implementation of a random num generator */
{
   public:
      int randomize() { return 0; }
};

class tSomeClass
{
   public:
      tSomeClass(RNG * rng) : fRNG(rng) { }

   private:
      RNG * fRNG;
};

...

RandomA randomObj;
tSomeClass t(&randomObj);

Or even a function pointer will do if that's all your random number generators consist of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM