【问题标题】:access to child template argument in base class (templated on the child class)访问基类中的子模板参数(在子类上模板化)
【发布时间】:2012-09-19 08:58:01
【问题描述】:

我有一个子类 (Child),它继承了以子类为模板的基类 (Base)。子类也是一个类型的模板(可以是整数或其他......),我试图在基类中访问这个类型,我尝试了很多东西但没有成功......这就是我的想法可能更接近可行的解决方案,但无法编译...

template<typename ChildClass>
class Base
{
    public: 
        typedef typename ChildClass::OtherType Type;

    protected:
        Type test;
};

template<typename TmplOtherType>
class Child
    : public Base<Child<TmplOtherType> >
{
    public:
        typedef TmplOtherType OtherType;
};

int main()
{
    Child<int> ci;
}

这是 gcc 告诉我的:

test.cpp:在“Base >”的实例化中:test.cpp:14:7:
从“子”实例化 test.cpp:23:16: 实例化自 这里 test.cpp:7:48: 错误: 在“类”中没有名为“OtherType”的类型 孩子”

这是一个等效的工作解决方案:

template<typename ChildClass, typename ChildType>
class Base
{
    public:
        typedef ChildType Type;

    protected:
        Type test;
};

template<typename TmplOtherType>
class Child 
    : public Base<Child<TmplOtherType>, TmplOtherType>
{
    public:
};

但困扰我的是重复的模板参数(将 TmplOtherType 作为 Childtype 转发)到基类...

你们怎么看?

【问题讨论】:

    标签: c++ templates generics typedef typename


    【解决方案1】:

    您可以使用template template parameter 来避免重复的模板参数:

    template<template<typename>class ChildTemplate, //notice the difference here
              typename ChildType>
    class Base
    {
      typedef ChildTemplate<ChildType>  ChildClass; //instantiate the template
      public:
        typedef ChildType Type;
    
      protected:
        Type test;
    };
    
    template<typename TmplOtherType>
    class Child 
        : public Base<Child, TmplOtherType> //notice the difference here also
    {
        public:
    };
    

    【讨论】:

    • 嗯,你是男人,它就像魔术一样工作;)顺便说一句,我不知道模板模板参数,太棒了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 2023-03-12
    • 2017-01-16
    • 1970-01-01
    相关资源
    最近更新 更多