我想其他人之前遇到过这个设计问题,所以我希望有人能给我一些建议:我有一个应该持有私有通用对象的类。据我所知,如果不将整个班级设为模板,我就无法逃脱。美好的。但是现在,有没有办法在构造过程中从构造函数参数推断底层对象的类型,而不显式指定它(我想省略模板参数Derived
,当我实例化Test
类时):
#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;
}
为了实现我的目标,我还应该了解其他设计策略吗?