Linux编译错误-GCC 4.3.4-模板参数列表太少

Linux compile error - GCC 4.3.4 - too few template-parameter-lists

本文关键字:参数 列表 错误 编译 -GCC Linux      更新时间:2023-10-16

我有一个非常小的标题,其中包含以下代码。该代码在Windows7中编译了6个月,但在linux中使用gcc 4.3.4失败。我试过几种方法使它发挥作用,但不幸的是什么都没发生。你们中有人知道可能出了什么问题吗?

问候

#ifndef UTILS_H
#define UTILS_H
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <algorithm>
template <class T>
unsigned int findUpperElement(const std::vector<T>& aVec, const T& aTargetValue)
{
    typedef std::vector<T>::const_iterator itType;
    itType itMatch=upper_bound (aVec.begin(),aVec.end(), aTargetValue);
    return std::distance<itType>(aVec.begin(),itMatch);
}
template <class T>
unsigned int findLowerElement(const std::vector<T>& aVec, const T& aTargetValue)
{
    typedef std::vector<T>::const_iterator itType;
    itType itMatch=lower_bound (aVec.begin(),aVec.end(), aTargetValue);
    return std::distance< itType> (aVec.begin(),itMatch);
}
#endif

以下是我得到的错误:

./utilslib/Utils.h: In function ‘unsigned int findUpperElement(const std::vector<T, std::allocator<_Tp1> >&, const T&)’:
./utilslib/Utils.h:15: error: too few template-parameter-lists
./utilslib/Utils.h:16: error: ‘itType’ was not declared in this scope
./utilslib/Utils.h:16: error: expected `;' before ‘itMatch’
./utilslib/Utils.h:17: error: ‘itType’ cannot appear in a constant-expression
./utilslib/Utils.h:17: error: ‘itMatch’ was not declared in this scope
./utilslib/Utils.h: In function ‘unsigned int findLowerElement(const std::vector<T, std::allocator<_Tp1> >&, const T&)’:
./utilslib/Utils.h:24: error: too few template-parameter-lists
./utilslib/Utils.h:25: error: ‘itType’ was not declared in this scope
./utilslib/Utils.h:25: error: expected `;' before ‘itMatch’
./utilslib/Utils.h:26: error: ‘itType’ cannot appear in a constant-expression
./utilslib/Utils.h:26: error: ‘itMatch’ was not declared in this scope

typename关键字添加到以下行:

typedef std::vector<T>::const_iterator itType;

更改为:

typedef typename std::vector<T>::const_iterator itType;

const_iterator是一个嵌套的依赖类型-嵌套在依赖它的模板参数类型中的类型。为了理解这种区别,你应该提供typename关键字-告诉编译器这是基于模板类型T的类型的名称。

编译器通常不会很正确地实现这一点——有些编译器会让你比其他编译器更轻松。

为了举例说明需要这样做的原因,请考虑以下内容:

T::X * var_name;

编译器可以将其解释为"我想要一个指向名为var_name的类型T::X的指针",也可以认为"我想要将类T中的静态变量X乘以var_name中的值"。

添加这样的类型名称:

typename T::X * var_name;

会迫使它更喜欢第一种,因为它现在知道T::X在这种情况下是一种类型。

我在代码中看到的最大问题是使用std::vector时没有包含vector的头文件。

#include <vector>添加到其中,看看这是否有帮助。