Wednesday, 7 August 2013

How do use a template object of any type

How do use a template object of any type

I have a template class:
template<class T>
class Request
{
public:
Request(T in) : m_data(in) {}
virtual ~Request() {}
T get() { return m_data; }
void set(T in) { m_data = in; }
private:
T m_data;
}
In another class I have the methods:
template<T>
void invoke(Request<T> request)
{
// Do some stuff
}
Request getRequest(int which)
{
switch(which)
{
case 1: return Request<int>(1);
case 2: return Request<bool>(true);
case 3: return Request<double>(2.0);
default: throw std::exception();
}
}
void run()
{
int type = getRequestType();
Request request = getRequest(type);
invoke(request);
}
The problem is this, the run() method cannot be templated, there must be
only 1 or them, and it needs to be able to deal with any type of request
it receives, as getRequestType() is reading the value from a file, which
can contain any type.
The compiler does not like this, it expects Request to have a type in
angled brackets, both in the run() method, and for the call to invoke().
It also expects the return type of getRequest() to have angled brackets.
Is there a C++ mechanism for holding and passing around a template object
of any type?

No comments:

Post a Comment