【问题标题】:Template issue in QtQt 中的模板问题
【发布时间】:2013-08-21 14:16:15
【问题描述】:

我尝试使用模板来定义一些类,如下所示:

.h

template <class T>
class QVecTemp
{
public:
    static QVector<QVector<T>> SplitVector<T>(QVector<T>, int);
private:
};

.cpp

    #include "QVecTemp.h"

template <class T>
QVector<QVector<T>> QVecTemp::SplitVector<T>(QVector<T> items, int clustNum)
{
    QVector<QVector<T>> allGroups = new QVector<QVector<T>>();

    //split the list into equal groups
    int startIndex = 0;
    int groupLength = (int)qRound((float)items.count() / (float)clustNum);
    while (startIndex < items.count())
    {
        QVector<T> group = new QVector<T>();
        group.AddRange(items.GetRange(startIndex, groupLength));
        startIndex += groupLength;

        //adjust group-length for last group
        if (startIndex + groupLength > items.count())
        {
            groupLength = items.Count - startIndex;
        }

        allGroups.Add(group);
    }

    //merge last two groups, if more than required groups are formed
    if (allGroups.count() > clustNum && allGroups.count() > 2)
    {
        allGroups[allGroups.count() - 2].append(allGroups.last());
        allGroups.remove(allGroups.count() - 1);
    }

    return (allGroups);
}

static QVector&lt;QVector&lt;T&gt;&gt; SplitVector&lt;T&gt;(QVector&lt;T&gt;, int); 上出现以下错误:

错误:'>>' 应该是嵌套模板参数列表中的 '> >'

错误:预期为 ';'在成员声明的末尾

错误:在 ' 之前的预期不合格 ID

真正的问题是什么?我该如何解决?

【问题讨论】:

    标签: c++ qt templates


    【解决方案1】:
    static QVector<QVector<T> > SplitVector(QVector<T>, int);
    

    你有两个错误。

    首先,在 C++03 中,&gt;&gt; 不能用于同时关闭两个模板参数列表,因为&gt; 必须用于关闭参数列表,而&gt;&gt; 与两个@987654325 是不同的标记@。在 C++11 中,此问题已得到修复。编译器给了你一个很好的错误信息:&gt;&gt; 应该是&gt; &gt;

    其次,类模板的成员函数在其名称后没有类的模板参数。它们不是模板专业化。编译器为此给了你一个可怕的消息:在它看到名称 SplitVector 后,它发现了一个 &lt;,它不存在(因为 SplitVector 不是已知的模板名称),所以编译器假设你正在声明一个名为 SplitVector 的数据成员,并且 ; 必须完成声明(这是第一条错误消息)。然后它再次查看&lt;,仍然无法理解它并给你一个更糟糕的信息,假装任何可能出现在代码中的任何东西都必须是某种名称。

    【讨论】:

    • 感谢您的回答。 >> 错误已修复,谢谢。关于第二个错误,其实我没有深入了解如何解决。
    • 我在 .h 和 .cpp 中都删除了,现在它在 .cpp 中的 QVector > QVecTemp::SplitVector(QVector items, int clustNum) 中出现以下错误: 错误: 'template class QVecTemp' 在没有模板参数的情况下使用
    • 应该是template &lt;class T&gt; QVector&lt;QVector&lt;T&gt; &gt; QVecTemp&lt;T&gt;::SplitVector(QVector&lt;T&gt; items, int clustNum)。模板参数放在类名之后,因为类是实际的模板,函数只是一个成员。
    【解决方案2】:
    static QVector<QVector<T> > SplitVector<T>(QVector<T>, int);
    

    【讨论】:

    • 嘿,你到底是什么意思?
    • @Mike 你的 c++ 编译器是什么?
    • @kw 我不确定......这不是我的电脑,但如果它对环境有帮助的话,Qt 5.1.0 正在 mingw48_32 上工作
    【解决方案3】:

    您的编译器已经非常简洁地告诉您问题所在:在 C++11 之前,您不能编写以下内容:

    some_class<other_class<int>> x; // error
    

    因为编译器会将该行中嵌套的&gt;&gt; 解释为&gt;&gt; 运算符。您需要额外的空间:

    some_class<other_class<int> > x; // this is ok
    

    请注意,较新的编译器(支持 C++11)不再存在此问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多