I am kind of C++ newbie, especially when dealing with templates. I have a template class "Foo" that is intended to take different structures as template parameters. I need also to have a member function of the class that works differently depending on the type template parameter, so I specialise such a function. The general picture would be as follows
struct A
{
float paramOfA;
};
struct B
{
float paramOfB;
};
template <typename T>
class Foo
{
public:
void doSomethingOnType(T& arg);
//...more functions and stuff...
};
// function specialisation for A's
template<> void Foo<A>::doSomethingOnType(A& a){
//do something on member of A
a.paramOfA = ...;
std::cout<< "I've done something on a's member..."<<std::endl;
}
// function specialisation for B's
template<> void Foo<B>::doSomethingOnType(B& b){
//do something on member of B
b.paramOfB = ...;
std::cout<< "I've done something on b's member..."<<std::endl;
}
So far so good, right? Imagine that now I have a structure C that derives from B:
struct C:B
{
float paramOfC;
};
Now, when I instantiate a Foo object that takes C structure template type, I would want the function "doSomethingOnType" to keep the same behaviour of the function for B types on C's member that derives from B (paramOfB), eventhough I haven't specialised such a function for C structure types. For instance
Foo<C> o;
C oneC;
o.doSomethingOnType(oneC);
I am sure that when executing the above piece of code, the function will take any implementation given in the templated class, not in the specialised version for B. But I really want to keep the latter implementation of the function when using C types since, being C derived from B, it would make a lot of sense to me as well as saving me time from having to write more lines of code for a function specialisation for C's that has the same behaviour than for B (imagine that B has 50 members instead of a single one). Is it possible to do so without, as I said, specialising the function for C structure types?
Thanks a lot in advance for any help!
Really excited to ask me first question in stackoverflow :-)