我正在尝试应用此处讨论的想法: http://www.drdobbs.com/cpp/dependency-injection-and-policy-based-de/228701135
代码或多或少如下:
class MyOtherClass
{
int m;
public:
MyOtherClass(int x) : m(x) { }
int DoSomething() { return m + 1; }
};
template<typename T>
struct DefaultFactory
{
T* Create() { return new T(); }
template<typename U>
T* Create(U x) { return new T(x); }
// ...
// add more versions of Create as needed
};
typedef MyOtherClass DefaultField;
typedef DefaultFactory<DefaultField> DefaultFact;
template<typename Field = DefaultField, typename Factory = DefaultFact>
class MyClass
{
public:
boost::scoped_ptr<Field> m;
MyClass() : m(Factory().Create(42)) { }
int DoSomething() { return m->DoSomething(); }
};
int main()
{
MyClass<DefaultField,DefaultFact> a;
cout<<"result="<<a.DoSomething()<<endl;
return 0;
}
它工作正常。然而,最后,通过将不同的策略分组到一个结构中,这个人用c ++ 11提出了一个更好的方法:
struct DefaultPolicy
{
typedef MyOtherClass Field;
typedef DefaultFactory<Field> Factory;
};
template<typename Policy = DefaultPolicy>
class MyClass
{
public:
boost::scoped_ptr<Field> m;
MyClass() : m(Factory().Create(42)) { }
int DoSomething() { return m.DoSomething(); }
};
但它对我不起作用。我尝试过以下方法:
struct DefaultPolicy
{
typedef MyOtherClass Field;
typedef DefaultFactory<Field> Factory;
};
template<typename Policy = DefaultPolicy>
class MyClass
{
public:
boost::scoped_ptr<Policy::Field> m;
MyClass() : m(Policy::Factory().Create(42)) { }
int DoSomething() { return m->DoSomething(); }
};
int main()
{
MyClass<DefaultPolicy> a;
a.DoSomething();
return 0;
}
我收到错误:
main.cxx:37:25: error: template argument for template type parameter must be a type; did you forget 'typename'?
boost::scoped_ptr<Policy::Field> m;
^
/include/boost/smart_ptr/scoped_ptr.hpp:41:16: note: template parameter is declared here
template<class T> class scoped_ptr // noncopyable
我在做什么?谢谢你的回复