gpt4 book ai didi

c++ - 如何使模板类向前声明

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:54:54 25 4
gpt4 key购买 nike

我计划了这个可爱的小设置(好吧,我认为它很可爱):

template< typename T>
class CInterfaceT
{
//a purely virtual interface declaration
};


template< typename T, typename SomeOtherStuff >
class CImplementationT : public CInterfaceT<T>
{
//implemenation stuff
};

然后:

typedef CInterfaceT<CFoo> IFooInterface;
typedef CInterface<CBar> IBarInterface;

class CObnoxiousHolder
{
public:
IFooInterface* GetFoo() { return &m_Foo; }
IBarInterface* GetBar() { return &m_Bar; }

private:
CImplementationT <CFoo, someting> m_Foo;
CImplementationT <CBar, otherting> m_Bar;
};

问题是,那些类型定义的“接口(interface)”必须在 C++ CLI 项目中使用,该项目依赖于以下内容来导入非托管代码:

class IFooInterface;
typedef IFooInterface CFooCppInterface;

这显然有效。或者用于使用正确声明的接口(interface)类,但现在不起作用,因为您不能转发声明模板实例。

下意识的解决方案是声明一些适当的接口(interface)类而不是 typedef:

class IFooInterface : public CInterfaceT<CFoo> {};
class IBarInterface : public CInterfaceT<CBar> {};

但这搞砸了类似 GetFoo() 的 getter 方法,因为这些新接口(interface)现在与正确的实现类几乎没有关系。

我仍然非常喜欢这里的模板方法,因为它节省了相当多的样板文件。我该如何解决?

编辑:解决方案很简单:使用更多模板!

template< typename T, typename Q, typename SomeOtherStuff >
class CImplementationT : public Q
{
//implemenation stuff
};

最佳答案

只是猜测 - 你需要这样的东西吗?

template<> class CInterfaceT<CFoo>;
typedef CInterfaceT<CFoo> CFooCppInterface;

代替;

class IFooInterface;
typedef IFooInterface CFooCppInterface;

不能向前声明的是部分专用模板。

关于c++ - 如何使模板类向前声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21250718/

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