I suppose some other folks ran into this design issue before so I hope someone could give me some advice on what to do: I have a class that is supposed to hold a private generic object. As far as I can tell, I can’t get away without making the entire class a template. FINE. But now, is there any way to infer the type of the underlying object during construction from the constructor parameter, without explicitly specifying it (I want to omit the template parameter, Derived, when I instantiate the Test class):
#include <iostream>
template <typename T>
class Generic
{
};
class Derived : public Generic<int>
{
public:
Derived ();
int GetFoo ();
private:
int m_foo;
};
template <typename T>
class Test
{
public:
Test (T &underlying);
private:
T m_underlying;
};
Derived::Derived ()
{
this->m_foo = 666;
}
int Derived::GetFoo ()
{
return this->m_foo;
}
template<typename T>
Test<T>::Test (T &underlying) : m_underlying(underlying)
{
std::cout << this->m_underlying.GetFoo() << std::endl;
}
int main ()
{
Derived underlying;
Test<Derived> test(underlying);
return 0;
}
Is there any other design strategy that I should be aware of, in order to achieve my goal?
Usually you have a class template together with a type-deducing function template:
Usage:
This idea is used countless times in the standard library (such as
make_pair,make_tuple,make_shared). The guiding principle is that you should say the desired typename at most one time, and not at all if it can be inferred.