C++ 如何声明自引用模板类型
我有一个类似这个人为的例子:C++ 如何声明自引用模板类型,c++,templates,C++,Templates,我有一个类似这个人为的例子: template<class TFeature> struct Controller {}; template<class TController,typename T> struct Feature { typedef Feature<TController,T> FeatureType; }; typedef Controller<Feature::FeatureType,int> DefaultContr
template<class TFeature> struct Controller {};
template<class TController,typename T> struct Feature {
typedef Feature<TController,T> FeatureType;
};
typedef Controller<Feature::FeatureType,int> DefaultController;
模板结构控制器{};
模板结构特征{
typedef特征类型;
};
typedef控制器DefaultController;
控制器被模板化以接受特性,我的问题是有些特性需要控制器的类型作为模板参数。这使得示例最后一行的typedef无法编译
这是可能的还是我需要重新考虑设计?一个选项是使用伪子类而不是typedef:
struct DefaultController : public Controller<Feature<DefaultController,int>::FeatureType> {};
struct DefaultController:public Controller{};
您正在向控制器
类传递两个模板参数,但您已声明它只接受一个。你需要像下面这样的东西吗
typedef Controller<Feature<Controller<int>,int>::FeatureType> DefaultController;
typedef控制器DefaultController;
似乎您正在尝试向控制器模板传递两个参数,而它只能接受一个。为了实现这一点,您应该做一些元编程魔术(相信我,这不是一项容易的任务)。但是如果你真的整理它,使用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;
模板
结构特征{
类型DEF ControlerT controler_类型;
};
模板
结构控制器{
typedef ControlerEx此_类型;
typedef typename boost::mpl::apply<
特性,boost::mpl::identity
>::类型特征\ U类型;
feature_type const&get_feature()const{return f_;}
私人:
特征类型f;
};
typedef ControlerEx DefaultControler;
@RondogiannisAristophanes,我认为这是问题的关键。为什么不能在结构外部声明FeatureType
?-1呈现的代码无效,使用两个实际的模板参数作为一个形式参数。这也是毫无意义的,因为Feature
typedef本身就是FeatureType
。我相信这是一种适合我的方法,我已经将其标记为我接受的答案。非常感谢所有花时间回答问题的人。