I am trying to implement a generic version of the code below:
#include <iostream>
class ContainerA
{
public:
ContainerA( int newData )
: mData_(newData)
{}
int mData_;
};
class ContainerB
{
public:
ContainerB( int newData )
: mData_(newData)
{}
int mData_;
};
ContainerA staticInstanceA( 3 );
ContainerB staticInstanceB( 11 );
template< ContainerA* ptrToContainer >
class WorkerOnA
{
public:
WorkerOnA( )
: mPtrToContainer_(ptrToContainer)
{}
void operator()()
{
std::cout << "Data = " << mPtrToContainer_->mData_ << '\n';
}
private:
ContainerA* mPtrToContainer_;
};
template< ContainerB* ptrToContainer >
class WorkerOnB
{
public:
WorkerOnB( )
: mPtrToContainer_(ptrToContainer)
{}
void operator()()
{
std::cout << "Data = " << mPtrToContainer_->mData_ << '\n';
}
private:
ContainerB* mPtrToContainer_;
};
int main( )
{
WorkerOnA<&staticInstanceA> workerOnAInstance;
WorkerOnB<&staticInstanceB> workerOnBInstance;
workerOnAInstance();
workerOnBInstance();
return 0;
}
What I would like to have (if this is possible at all) is a single Worker template-class, which can be instantiated to work on either container, something like:
template< ?? ptrToContainer >
class WorkerOnAnyContainer
{
public:
WorkerOnA( )
: mPtrToContainer_(ptrToContainer)
{}
void operator()()
{
std::cout << "Data = " << mPtrToContainer_->mData_ << '\n';
}
private:
?? mPtrToContainer_;
};
However, after several hours, I still can't figure what the '??'s should be. Maybe a template-wizard has an idea?
Update 1: Fixed mistake in 'operator()' of Workers (ptrToContainer -> mPtrToContainer_). Sorry for that.
Update 2: I got something working, but I would still be curious if anyone has a better idea. For example, having a single template-parameter would be nice. Does anyone know if "template template parameters" can help in this situation?
template< class TContainer, TContainer* ptrToContainer >
class Worker
{
public:
Worker( )
: mPtrToContainer_(ptrToContainer)
{}
void operator()()
{
std::cout << "Data = " << mPtrToContainer_->mData_ << '\n';
}
private:
TContainer* mPtrToContainer_;
};
Thanks, D