A template question: Can compiler deduce template type in static method
I have the following setup:
A templated class SpecialModel:
template<typename A, typename B>
class SpecialModel<A, B> {
};
A templated Worker, working on some kind of Model:
template<typename M>
class Worker<M> {
Worker(M& model);
void work();
};
And a speciali开发者_JAVA百科zation of Worker for SpecialModel:
template<typename A, typename B>
class Worker<SpecialModel<A, B> > {
Worker(SpecialModel& model);
void work();
};
Finally, there is a class that handels a given worker through a static method, basically this Manager class does lots of administration things to allow Worker focus on the real work:
template<typename W>
class Manager<W> {
Manager() {};
static void getThingsDone(W worker) {
...;
worker.work();
...;
};
};
To 'getThingsDone' for a SpecialModel, I need the following in the code:
SpecialModel<A1, B1> spmo;
Worker< SpecialModel<A1, B1> > w(spmo);
Manager<Worker< SpecialModel<A1, B1> > >::getThingsDone(w);
The last line is the one I have problems with. Isn't there a way to just say:
Manager::getThingsDone(w);
Can't the compiler deduce the type of W from w?
Why do i want that, anyway? I have an array of Workers, working on different kinds of SpecialModels (different As and Bs). Now i want to loop over this array, calling Manager::getThingsDone(w) on each worker. How should i be able to pass typeinformation on to Manager, when only having the array of workers? (The array of SpecialModles is known at compile time (part of this code is autogenerated and then compiled for this kind of special input), the array will be defined somewhere at the toplevel of the code, yet, the code doing the work should be as general as possible. However, i would be happy to find an answer without regard to this last point).
If Train is a templated class, as it appears to be, the compiler cannot deduce class templates from static method template arguments.
If Train::train is a static method, why is your class Train templated? Method train cannot access any member variables anyway. You could probably make train a free function:
template<class W>
void train(W const& w) { ... }
And in your code you could simply do
train(w);
If class Train must be templated with type Worker, you could write a helper function that can discover the template parameter automatically:
template<class W>
Train<W> make_trainer(W const& w) { return Train<W>(w); }
You can also make train a static function of class Train with its own template parameter:
class Train {
template<class W>
vod train(W const& w) { ... }
};
Your code could then call
Train::train(w);
What's best depends on your exact use case.
精彩评论