如何声明自我引用模板类型

How to declare a self referencing template type

本文关键字:引用 类型 自我 何声明 声明      更新时间:2023-10-16

我有一个像这个人为示例的情况:

template<class TFeature> struct Controller {};
template<class TController,typename T> struct Feature {
  typedef Feature<TController,T> FeatureType;
};
typedef Controller<Feature::FeatureType,int> DefaultController;

控制器被模板接受以接受功能,我的问题是某些功能需要控制器的类型作为模板参数。这使得在样本的最后一行中的Typedef不编译。

这是可能的还是我需要重新考虑设计?

为了实现此目的,您应该做一些元编程魔术(相信我这不是一件容易的事)。但是,如果您真的钉住它并且使用boost是一个选择,请看一下boost::mpl,您可以拥有这样的东西:

template< class ControlerT >
struct FeatureEx {
    typedef ControlerT controler_type;
};
template< class FeatureT >
struct ControlerEx {
    typedef ControlerEx<FeatureT> this_type;
    typedef typename boost::mpl::apply<
        FeatureT, boost::mpl::identity<this_type>
    >::type feature_type;
    feature_type const& get_feature() const {return f_;}
private:
    feature_type f_;
};
typedef ControlerEx<FeatureEx<boost::mpl::placeholders::_1> > DefaultControler;

您将传递给Controller类别两个模板参数,但您已声明它仅需一个。您需要以下内容吗?

typedef Controller<Feature<Controller<int>,int>::FeatureType> DefaultController;

一个选项是使用虚拟子类代替typedef:

struct DefaultController : public Controller<Feature<DefaultController,int>::FeatureType> {};

似乎您正在尝试将2个参数传递给控制器模板,而它只能接受一个。