views:

93

answers:

2

Hi All, I'm trying to implement a function that allows me to make a call like this

// veca is a vector of tuples in my case
columnViewOfTuple<0>(veca);

I implemented such function as follows

template<int N>
struct myfunction {
    template<typename T, typename R>
    std::vector<R> operator() (T& container)
    {
        std::vector<R> myvector;
        for(typename T::iterator it = container.begin(); it!=container.end(); it++)
            myvector.push_back((R)(*it).template get<N>());
        return myvector;
    }
};

whenever I call myfunction<0>(vec5), where vec5 is some vector of tuples, it says

main.cpp: In function 'int main()': main.cpp:156: error: conflicting declaration 'myfunction<0> vec5' main.cpp:155: error: 'vec5' has a previous declaration as 'main()::vec1_t vec5'

Do you guys know how to fix this?

Thanks

+2  A: 

You need to use typename in front of T::iterator. So say typename T::iterator.

Edit1 including template as indicated by Johannes to prevent misinformation.

So, your code should be like this:

template<int N>
struct myfunction {
    template<typename T, typename R>
    std::vector<R> operator() (T& container)
    {
        std::vector<R> myvector;
        for(typename T::iterator it = container.begin(); it!=container.end(); it++)
            myvector.push_back((R)(*it).template get<N>());
        return myvector;
    }
};
JoshD
thank you, that was helpful. However, I tried to use the function
Banana
+5  A: 

The loop should be

    for(typename T::iterator it = container.begin(); it!=container.end(); it++)
        myvector.push_back((R)(*it).template get<N>());

Otherwise, the compiler will treat T::iterator as a non-type (at parse-time, it does not yet know what T::iterator is going to be later!) and will likely parse it as the sole constituent of an expression. The it that then follows is nonsense for the compiler so it expects a ; before it.

typename is used to tell the compiler that a certain qualified name is intended to denote a type instead of a value (function / static data member / etc).

The second issue, which is solved by adding template is of similar kind. It tells the compiler that get is a template and thus that <N is not a comparison against N, but the start of a template argument list.

Johannes Schaub - litb
+1: spotting missing `typename` and missing `template`.
Charles Bailey
+1 for that template piece (and a good answer overall). Sadly, I didn't know this myself.
JoshD