【发布时间】:2013-04-08 13:29:22
【问题描述】:
我正在使用 CRTP 模式创建一个接口,其他类将从该接口派生。
在界面中,我转发声明了一个结构(这很重要,因为我不想在界面中拖动其他东西),但我将其定义包含在定义界面的 cpp 文件中。
Interface.h
#ifndef INTERFACE_H_INCLUDED
#define INTERFACE_H_INCLUDED
// forward declaration
class ForwardDecl;
template <class Derived>
class Interface
{
public:
ForwardDecl interfaceMethod();
};
#endif // INTERFACE_H_INCLUDED
ForwardDecl.h
#ifndef FORWARDDECL_H_INCLUDED
#define FORWARDDECL_H_INCLUDED
struct ForwardDecl
{
ForwardDecl(int i):internal(i)
{}
int internal;
};
#endif // FORWARDDECL_H_INCLUDED
Interface.cpp
#include "Interface.h"
#include "ForwardDecl.h"
template<class Derived>
ForwardDecl Interface<Derived>::interfaceMethod()
{
return static_cast<Derived *>(this)->implementation_func();
}
这是实现接口的实现
实施.h
#ifndef IMPLEMENTATION_H_INCLUDED
#define IMPLEMENTATION_H_INCLUDED
#include "Interface.h"
class ForwardDecl;
class Implementation: public Interface<Implementation>
{
friend class Interface<Implementation>;
private:
ForwardDecl implementation_func();
};
#endif // IMPLEMENTATION_H_INCLUDED
实施.cpp
#include "Implementation.h"
#include "ForwardDecl.h"
#include <iostream>
struct ForwardDecl Implementation::implementation_func()
{
ForwardDecl fd(42);
std::cout << fd.internal << std::endl;
return fd;
}
还有主文件
#include <iostream>
#include "Implementation.h"
#include "ForwardDecl.h"
using namespace std;
int main()
{
Implementation impl;
ForwardDecl fd = impl.interfaceMethod();
cout << fd.internal << endl;
return 0;
}
我在 VS 和 GCC 上都遇到链接错误。
有什么解决方法吗?谢谢。
【问题讨论】:
-
在界面中进行前向声明是这里的重点,如果不是这样,我会将所有内容移动到头文件中。
-
使用模板 interface 定义和指针可以实现您正在尝试做的事情(如果我理解的话,那是不确定的),但是像这样的实例级我我很难看到它起作用。
标签: c++ templates design-patterns crtp