【问题标题】:Problem with template specialization and template template parameters模板特化和模板模板参数的问题
【发布时间】:2010-09-26 02:27:00
【问题描述】:

我有一堂课Helper:

template <typename T, template <typename> E>
class Helper {
    ...
};

我有另一个类模板Exposure,它继承自Helper,同时将自身作为模板模板参数E 传递。我还需要专攻Exposure。因此,我想写如下内容:

template <>
class Exposure<int> : public Helper<int, Exposure> {
    Exposure() : Helper<int, Exposure>() {
        ...
    };
    ...
};

不幸的是,这不会编译。 gcc 抱怨:

Exposure.h:170: 错误:“模板 > 类 ExposureHelper”的模板参数列表中参数 2 的类型/值不匹配

Exposure.h:170: 错误:期望一个''类型的常量,得到'Exposure'

我做错了吗?我正在尝试做的事情有解决方法吗?

【问题讨论】:

    标签: c++ templates template-specialization


    【解决方案1】:

    如果你真的想传递 template 而不是 class

    template <typename T, template<typename> class E>
    class Helper {
    };
    
    template <typename T>
    class Exposure;
    
    template <>
    class Exposure<int> : public Helper<int, Exposure > {
    };
    

    或者如果你的意图不同

    template <typename T, typename E>
    class Helper {
    };
    
    template <typename T>
    class Exposure;
    
    template <>
    class Exposure<int> : public Helper<int, Exposure<int> > {
    };
    

    【讨论】:

      【解决方案2】:

      在你的Helper的第一个模板中,你不需要说第二个参数是一个模板:

      template <typename T, typename E>
      class Helper {
          ...
      };
      

      您可以使用模板作为参数声明一个:

      Helper<vector<int>, vector<char> > h;
      

      但是在您的第二个模板中,您有一个循环定义。您的 Exposure 等级取决于您的 Exposure 等级。这会创建一个循环引用,Helper 类需要先定义 Exposure,然后才能从 Exposure 继承。你可能需要重组你的类。

      【讨论】:

        猜你喜欢
        • 2017-01-20
        • 2015-02-19
        • 2011-05-10
        • 2018-06-25
        • 1970-01-01
        • 2017-10-15
        • 2018-11-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多