1

我想出了我自己的小类 TinyVector。现在我正在尝试使用 std::inner_product 。但我无法让它工作,我不明白为什么这不起作用。我正在使用 Visual Studio 2012。

#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

template<class T, int N>
class TinyVector {
public:
    TinyVector() { data = vector<T>(N, 0); }
    explicit TinyVector(const T initVal) { data = vector<T>(N, initVal); }
    ~TinyVector() { data.clear(); }
    inline T& operator[](int i) { return data[i]; }
    inline T operator[](int i) const { return data[i]; }
    inline vector<T>::const_iterator begin() const { return data.begin(); } //Line 15
    inline vector<T>::const_iterator end() const { return data.end(); } //Line 16
private:
    vector<T> data;
};

template<class T, int N>
inline double dot(const TinyVector<T,N>& A, const TinyVector<T,N>&  B)
{
    return inner_product(A.begin(), A.end(), B.begin(), 0.0);
}

int main()
{
    TinyVector<double, 10> Ty;
    for (int i = 0; i < 10; ++i)
        Ty[i] = i;

    cout << dot(Ty,Ty) << endl;
}

编译器告诉我:语法错误:缺少';' 在第 15 行的标识符“开始”之前。缺少类型说明符 - 假定为 int。注意:C++ 不支持第 15 行的 default-int。语法错误:缺少 ';' 在第 16 行的标识符“结束”之前。缺少类型说明符 - 假定为 int。注意:C++ 在第 16 行不支持 default-int。

But changing vector<T>::const_iterator into vector::const_iterator doesn't seem like the way to go. Also changing it to 'auto' does not work. This gives me "expected a trailing return type". If I delete line 15,16 and 17 and replace A.begin() with A.data.begin() and the next two arguments accoringly, everything is fine. But why doesn't my original code work, and how can I get it to work?

4

1 回答 1

5

You need to write

inline typename vector<T>::const_iterator begin() const { return data.begin(); } //Line 15
       ^^^^^^^^

This is because vector<T>::const_iterator is a dependent name (it is dependent on the type parameter T) and so the compiler needs to be told that vector<T>::const_iterator is a type (and not, say, an enum value or static data member).

于 2012-10-19T12:12:32.273 回答