template specialization

A

alariq

Hello, i have a class Builder and several objects to build.
Builder {
A* buildA();
B* buildB();
C* buildC();
D* buildD();
//... more objects may come
}

there may be more classes to build in future. Some classes has to be
created in one way(A,B, ...) and others(C,D,,) in another way.
I am thinking of templates, but i can only specialize them for 1 class
so if even A and B should behave in the same way I should manually
specialize template for them
like this:

Builder {
template <typename T> T* build();
};

template<> A* Builder::build<A>() { // do job1 }
template<> B* Builder::build<B>() { // do same job1 }

template<> C* Builder::build<C>() { // do job2 }
template<> D* Builder::build<D>() { // do same job2 }

so anyway 4 functions instead of 2.
i also was thinking about making common parent for (A & B) and (C &
D) and use it as second template parameter but there is no partial
specialization for functions and i do not wand to make same parent
because A and B are not really similar thay just have to be created in
same way (this also applies for D and D)

maybe someone can give me an advice?

p.s. just fugured out that i can create build1() and build2() template
member functions and call them, but it would be better to have only
one.
p.p.s other way is to specialize build() 4 times to call build1/build2
depending on its type - ugly but specialization code will be small,
e.g.
template<> A* Builder::build<A>() { build1<A>(); }
template<> B* Builder::build<B>() { build1<B>(); }

template<> C* Builder::build<C>() { build2<C>() }
template<> D* Builder::build<D>() { build2<D>() }

but anyway it is not very clear solution, i guess...

is there any other?

Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top