gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:36:45 25 4
gpt4 key购买 nike

我有一个 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’

是否有可能使用模板来实现它?还是继承实现类层次结构是唯一的方法?

最佳答案

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

关于c++ - 如何修复/重新设计模板递归依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27174101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com