Passing a template class with an unknown type to an unoccupied class constructor

I have two classes, let's call them SomeClass and OtherClass.

SomeClass Templates:

template <typename T> class SomeClass
{
public:
    SomeClass (const T& value);
};

OtherClass is not a template, but uses SomeClass.

class OtherClass
{
public:
    OtherClass (const SomeClass& c, const std::string s);
};

They should be called as follows:

SomeClass<int> some(5);
OtherClass other(some, "hello, world!");

other.doSomethingWithSome();

... Obviously, this does not compile, since the compiler must know the type of SomeClass ...

Unfortunately, for me, the SomeClass type can be almost anything (although the number of actual types used is limited, it is simply not related) and can often change during development. (I know, I know, I believe that I could really use the SomeClass type and pass it to the templated OtherClass, but its pretty tedious work, as there are a few examples, I would also like to pretend that no class knows about other jobs.:))

: ? ( templatize OtherClass.)

+2
5

, SomeClass :

template <typename T>
class SomeClass : public SomeAbstractBase
{
    /* ... */
};

, , OtherClass SomeAbstractBase:

class OtherClass
{
public:
    OtherClass (const SomeAbstractBase& c, const std::string s);
};

, , , . , SomeAbstractBase (.. , SomeClass<T>), , , .

+6

:

class OtherClass
{
public:
  template < typename T >
  OtherClass(SomeClass<T> const& c, std::string const& s)
    : pimpl(new impl<T>(c))
    , str(s)
  {}

  void doSomething() { pimpl->doSomething(str); }

private:
  struct impl_base { virtual ~impl_base() {} virtual void doSomething(std::string) { ... }};
  template < typename T >
  struct impl : impl_base
  {
    impl(T const& )...
  };

  scoped_ptr<impl_base> pimpl;
};
+2

templatize OtherClass, OtherClass, SomeClass, .

// Otherclass can take objects of any type now
template <typename T> class OtherClass
{
public:
    OtherClass(SomeClass<T>& someclass..);
};

// or

class OtherClass
{
    // specialize the otherclass constructor
    OtherClass(SomeClass<int> someclass ..)
}
+1
source

It is not clear what exactly you are trying to do. But what about the template constructor?

class OtherClass {
public:
  template <typename T> OtherClass(const SomeClass<T>& c, const std::string& s);
  // ...
};

Of course, this will not work if, for example, OtherClassa type member is needed SomeClass<T>.

0
source

Use both compilation time (templates) and runtime polymorphism (virtual):

class MyBase {
public: 
   virtual void foo() = 0;
}


template <class T>
class SomeClass : public MyBase {
public:

   void foo () {
     // do T-specific stuff
   }
}

OtherClassthen accepts MyBase*and OtherClass::doSomethingWithSomecalls its virtual foomethod.

0
source

Source: https://habr.com/ru/post/1781509/


All Articles