C++接口的工厂函数实现

C++ interface's factory function implementation

本文关键字:函数 实现 工厂 接口 C++      更新时间:2023-10-16

上下文化:

我正在研究一种面部识别算法,NIST是试图标准化所有可用算法之间的测试,测量和比较的组织。为了进行测试和比较,我需要实现它们的接口,该接口在 FRVT 项目中可用,更具体地说是在 frvt11.h 文件中。

frvt11.h此问题的相关代码:

namespace FRVT {
//...A lot of code defining ReturnStatus, ReturnCode, etc.
/**
* @brief
* The interface to FRVT 1:1 implementation
*
* @details
* The submission software under test will implement this interface by
* sub-classing this class and implementing each method therein.
*/
class Interface {
public:
virtual ~Interface() {}
virtual ReturnStatus
initialize(const std::string &configDir) = 0;
/**
* @brief
* Factory method to return a managed pointer to the Interface object.
* @details
* This function is implemented by the submitted library and must return
* a managed pointer to the Interface object.
*
* @note
* A possible implementation might be:
* return (std::make_shared<Implementation>());
*/
static std::shared_ptr<Interface>
getImplementation();
};
}

实现.h我正在开发的实现的相关代码:

#include "frvt11.h"
using namespace FRVT;
struct Implementation : public Interface {
ReturnStatus
initialize(const std::string &configDir) override;
static std::shared_ptr<Interface>
getImplementation();
};

实现.cpp我正在开发的实现的相关代码:

#include "implementation.h"
using namespace FRVT;
ReturnStatus
Implementation::initialize(
const std::string &configDir) {
return ReturnStatus(ReturnCode::Success," - initialize");
}
std::shared_ptr<Interface>
Implementation::getImplementation() {
return (std::make_shared<Implementation>());
}

最后我的问题:

问题:如何实现getImplementation((以返回引用的"指向接口对象的托管指针"?

我认为你可以做到以下几点:

std::shared_ptr<Interface> Implementation::getImplementation() {
return std::make_shared<Implementation>();
}
int main() {
auto interface = Implementation::getImplementation();
}

interface将是std::shared_ptr<Interface>型.您可以进一步传递它。