gpt4 book ai didi

c++ - 模板参数重新声明

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:41:31 25 4
gpt4 key购买 nike

这就是我想要实现的。叶子组件会继承Component<ParentT> ,其他人将继承Component<ParentT, ChildT>

template <typename T>
class Component{
protected:
typedef Component<T> ParentComponentT;
...
};

template <typename ParentT, typename ChildT>
class Component: public Component<ParentT>{
protected:
typedef std::vector<ChildT*> CollectionT;
...
};

但问题是模板参数被重新声明。我不能将第二个移动到第一个之上,因为第二个继承了第一个。

error: redeclared with 2 template parameter(s)
note: previous declaration ‘template class Component’ used 1 template parameter(s)

最佳答案

这会编译,据我所知会做你喜欢的事情:

#include <vector>

class NoneT {};

template <typename ParentT,typename ChildT=NoneT>
class Component: public Component<ParentT>{
protected:
typedef std::vector<ChildT*> CollectionT;
};

NoneT 的特化:

template<>
template<typename T>
class Component<T,NoneT>{
protected:
typedef Component<T> ParentComponentT;
};

int main(){
typedef Component<double> someT;
typedef Component<double,int> someT2;
typedef Component<double,void> someT3;
}

someT 将具有 ParentComponentTsomeT2 将具有 CollectionT

编辑:

以下评论/问题的答案:typename ChildT=noneT 表示默认的 ChildT 将是 noneT。因此,如果没有给出第二个模板参数,则将使用 noneT 类型。

特化然后为该单参数版本定义类内容。

编辑 2:

因为我从聊天中知道您使用 Component 作为基类,所以我建议不要像

class myclass: public Component<Section, Line>

你可以使用多重继承

class myclass: public ParentComponent<Section>, CollectionComponent<Line>

template <typename T>
class ParentComponent{
protected:
typedef Component<T> ParentComponentT;
};

template <typename ChildT>
class CollectionComponent {
protected:
typedef std::vector<ChildT*> CollectionT;
};

关于c++ - 模板参数重新声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11814447/

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