简体   繁体   English

如何声明自引用模板类型

[英]How to declare a self referencing template type

I've a situation that is like this contrived example: 我的情况就像这个人为的例子:

template<class TFeature> struct Controller {};

template<class TController,typename T> struct Feature {
  typedef Feature<TController,T> FeatureType;
};

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

The Controller is templated to accept features and my problem is that some of the features need the type of the controller as a template parameter. Controller模板化接受功能,我的问题是某些功能需要控制器的类型作为模板参数。 This makes the typedef on the last line of the sample not compile. 这使得样本最后一行的typedef无法编译。

Is this possible or do I need to rethink the design? 这是可能的还是我需要重新考虑设计?

In order to accomplish this you should do some meta programming magic(and believe me it is not an easy task). 为了实现这一点,你应该做一些元编程魔术(相信我这不是一件容易的事)。 But if you really nead it and using boost is an option for you take a look at boost::mpl and you can have something like this: 但是,如果你真的知道它并使用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;

You are passing to the Controller class two template parameters, but you have declared it to take only one. 您正在向Controller类传递两个模板参数,但您已声明它只采用一个。 Do you need something like the following? 你需要以下的东西吗?

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

一种选择是使用虚拟子类而不是typedef:

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

似乎你试图将2个参数传递给你的控制器模板,而它只能接受一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM