如何声明自我引用模板类型
How to declare a self referencing template type
我有一个像这个人为示例的情况:
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个参数传递给控制器模板,而它只能接受一个。
相关文章:
- 强制转换为引用类型
- 自定义引用类型
- Java 中是否有类似于 C++ 中引用类型"&"的内容?
- 为什么我不能在运算符=中使用引用类型?
- 可变参数模板函数参数和引用类型推导
- 隐式可转换参数,但属于引用类型
- 如何告诉自动推断向量<bool>元素的非引用类型
- 为什么"const auto [x, y]"绑定到引用类型时没有按预期运行?
- 引用类型的数据成员提供有关恒常正确性"loophole"
- 为什么引用类型在使用临时对象访问时是左值
- 什么是常量指针常量引用类型的参数?(const X* const & p)
- 在 lambda 中从引用类型捕获的值的类型,不使用通用捕获
- 如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
- void*作为通用引用类型是如何工作的
- 强制转换为不相关的引用类型是否违反严格的别名规则?
- C++ 引用类型作为递归函数参数
- EXPECT_CALL具有 unique_ptr 引用类型参数的模拟函数
- 如果使用返回引用的函数初始化"auto"var,为什么它不声明引用类型?
- 为什么模板引用类型不能用作模板类型别名参数?
- 模板默认参数将丢失其引用类型