如何修复/重新设计模板递归依赖

时间:2014-11-27 15:27:46

标签: c++ templates

我有一个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类层次结构是唯一的方法吗?

1 个答案:

答案 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;
};