1

I am trying to pass a template typedef as argument to a function template. However I get following errors:

TestTemplates.cpp:11: error: expected unqualified-id before ‘&’ token

TestTemplates.cpp:11: error: expected unqualified-id before ‘&’ token

TestTemplates.cpp:11: error: expected initializer before ‘&’ token

TestTemplates.cpp:25: error: ‘func’ was not declared in this scope

#include <iostream>
#include <vector>

template<class T>
struct MyVector
{
    typedef std::vector<T> Type;
};

template<class T>
void func( const MyVector<T>::Type& myVec )
{
    for( MyVector<T>::Type::const_iterator p = myVec.begin(); p != myVec.end(); p++)
    {
        std::cout<<*p<<"\t";
    }
}

int main()
{
    MyVector<int>::Type myVec;
    myVec.push_back( 10 );
    myVec.push_back( 20 );

    func( myVec );
}

Can anyone point out how to fix this error. I have looked at some posts, but cannot find the solution. Thanks

Community
  • 1
  • 1
nurabha
  • 1,152
  • 3
  • 18
  • 42
  • [Non-deducible context](http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Stephan-T-Lavavej-Core-C-2-of-n) and [this](http://stackoverflow.com/q/610245/500104). – Xeo Aug 12 '12 at 13:50

1 Answers1

3

You need to tell the compiler that it's a typename

void func( const typename MyVector<T>::Type& myVec )

Then you need to explicitly help the compiler deduce the type for the function:

func<int>( myVec );

BTW, the issue is called "two stage lookup"

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
  • No, that will still not solve it. `func`'s `myVec` parameter is in a non-deducible context. – Xeo Aug 12 '12 at 13:50
  • 1
    @Xeo is right, it is in a non-deducible context, however with explicit type specification it could be done: http://ideone.com/ZpRj5. – Greg Aug 12 '12 at 13:57
  • Yes, I get some more errors. "TestTemplates.cpp:13: error: expected ‘;’ before ‘p’", "TestTemplates.cpp:13: error: ‘p’ was not declared in this scope", "TestTemplates.cpp:25: error: no matching function for call to ‘func(std::vector >&)’" – nurabha Aug 12 '12 at 13:58
  • Oh yes, thanks. It works now. I never really have worked with typename. Can you point me to a tutorial on working of typename? – nurabha Aug 12 '12 at 14:00
  • @nurav : I've edited the answer for the explicit function type when calling the function. – Yochai Timmer Aug 12 '12 at 14:03
  • @Xeo: you're right, i didn't read the whole thing till the end when i first answered, just solved the error messages he gave. – Yochai Timmer Aug 12 '12 at 14:04
  • @nurav : I've added a link that describes the issue. – Yochai Timmer Aug 12 '12 at 14:10