Nikhil Augustine Nikhil Augustine - 1 month ago 5
C++ Question

Passing object of a template class to constructor of another class

I have a template class,

template< typename T >
class A
{
private:
T *array;
public:
A(int size)
{
//Initialises array with size
}
}


Now I need to have a class B which receives object of class A as constructor argument and assigns it to B local member of A reference. How do I do that? I have tried like,

class B
{
private:
template<class T>
A<T> *a;
public:
template<class T>
B(A<T>(int) ar){
//assign ar to a
}
}


Can somebody help me to solve this problem?

UPDATE
Actually what I want to achieve here is, think that class A is a generic circular buffer, which can be initialised in one shot like
A< int > int_buffer(20);
and the same int_buffer to be used across different classes say B and C(Producer and Consumer). Is this the correct way to achieve my goal or any better approach you can suggest.

Answer

You'll just need to make B a template as well:

template <typename T>
class B {
    A<T>* a;
public:
    B(A<T>* ar) : a(ar) {}
};

This runs upon the problem of shared pointers. It's unclear to me as the reader if B<T> will depend upon an A<T>* that is externally owned, or if the ownership of A<T>* is also being transfered to B<T>. C++11 has provided you some great tools for sharing pointers, and I'd strongly recommend that you take advantage of them.

If you want to share A<T>* but it will be owned externally use a shared_ptr.
If you transferring ownership of A<T>* on construction, signify that by using a unique_ptr.

Comments