我有一个Process
课程,想要使用模板与其中一个Implementation
配对。
过程:
template <typename ImplementationType>
class Process
{
public:
Process() : pid(0), _impl(*this) { }
int execute() { _impl.execute(); }
int getPid() { return pid; }
private:
ImplementationType _impl;
// process specific details
int pid;
};
SimpleProcessImplementation :
template <typename ImplementationType>
class SimpleProcessImplementation
{
public:
SimpleProcessImplementation(Process<ImplementationType>& process) : _process(process) { }
int execute() { std::cout << "Simple implementation of Process " << _process.getPid() << "\n"; }
private:
Process<ImplementationType>& _process;
};
我打算用它作为:
Process<SimpleProcessImplementation> p; // Line 50
p.execute();
从示例中可以看出,SimpleProcessImplementation
显然存在递归依赖,无法编译程序。
template.cpp:50:40: error: type/value mismatch at argument 1 in template parameter list for ‘template<class ImplementationType> class Process’
template.cpp:50:40: error: expected a type, got ‘SimpleProcessImplementation’
template.cpp:50:43: error: invalid type in declaration before ‘;’ token
template.cpp:51:7: error: request for member ‘execute’ in ‘p’, which is of non-class type ‘int’
是否可以使用模板实现此功能?或继承Implementation
类层次结构是唯一的方法吗?
答案 0 :(得分:2)
SimpleProcessImplementation
不是一个类(它是一个类模板),因此它不适合Process
的模板参数槽,并且编译器抱怨这一点。我想你的意思是
class SimpleProcessImplementation
{
public:
SimpleProcessImplementation(Process<SimpleProcessImplementation>& process) : _process(process) { }
int execute() { std::cout << "Simple execution of Process " << _process.getPid() << "\n"; }
private:
Process<SimpleProcessImplementation>& _process;
};