【问题标题】:C++ Function Nested TemplatesC++ 函数嵌套模板
【发布时间】:2014-04-29 10:56:08
【问题描述】:

我想写一个可以同时接收任何类型的 QList 和 QVector 的函数:

QList<int> iList;
QVector<int> iVector;
QList<double> dList;
QVector<double> dVector;

所有这些类型都必须支持调用

my_func(iList); my_func(iVector); my_func(dList); my_func(dVector);

我的解决方案

template <template <typename Elem> typename Cont>
void my_func(const Cont& cont)
{
    qDebug() << cont.isEmpty();
    Elem el = cont.first();
    qDebug() << el;
}

未编译:

error C2988: unrecognizable template declaration/definition

这样的模板函数的正确形式是什么?

【问题讨论】:

    标签: c++ templates sfinae generic-programming qlist


    【解决方案1】:

    您的代码中有几个错误:

    template <template <typename> class Cont, typename Elem>
    //                            ^^^^^       ^^^^^^^^^^^^^
    void my_func(const Cont<Elem>& cont)
    //                     ^^^^^^
    {
        qDebug() << cont.isEmpty();
        Elem el = cont.first();
        qDebug() << el;
    }
    

    【讨论】:

      【解决方案2】:

      编译器在尝试定位匹配时只考虑主类模板,因此它不知道Elem 是什么,

      Elem el = cont.first();
      

      因为Elem 不是专业化的。

      使用以下任一解决方案,

      template <class Elem, template <class> class Cont>
      void my_func(const Cont<Elem>& cont) { ... }
      
      template <class Cont> void my_func(const Cont& cont) {
          typename Cont::value_type el = cont.first();
      }
      

      【讨论】:

      • Cont::value_type 应该是typename Cont::value_type
      • 这里有一个错字:my_func(const Cont&amp; cont); {.
      【解决方案3】:

      您不需要指定嵌套模板参数,您可以使用auto 来检索元素。

      template <typename Cont>
      void my_func(const Cont& cont)
      {
          qDebug() << cont.isEmpty();
          auto el = cont.first();
          qDebug() << el;
      }
      

      请注意,编译时需要指定 C++0x 或 C++11 标准。

      【讨论】:

        猜你喜欢
        • 2013-12-20
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 2018-11-08
        • 2019-10-28
        • 1970-01-01
        • 2020-09-17
        • 2015-07-03
        相关资源
        最近更新 更多