0

Just ran into weird problem with templates while porting code from Windows to Linux.

Provided sample compiles with MSVC and works flawlessly.

Code sample:

#include <vector>
#include <iostream>

typedef std::vector<int> IntArray;

template <typename TArray>
void printArray(TArray a)
{
    typedef TArray::iterator iter;
    for (iter it = a.begin(); it != a.end(); ++it)
        std::cout << *it << std::endl;
}

int main()
{
    IntArray a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    printArray(a);
    return 0;
}

But g++ complains that

In function ‘void printArray(TArray)’:
bar.cpp:9: error: expected initializer before ‘iter’
bar.cpp:10: error: ‘iter’ was not declared in this scope
bar.cpp:10: error: expected ‘;’ before ‘it’
bar.cpp:10: error: ‘it’ was not declared in this scope

After an hour of asking Google I have no idea what's going on.

e_ChiP
  • 73
  • 1
  • 5
  • @Casey, i think this my question is not duplicate of [yours](http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) because it is sort of an _answer_ to mine. – e_ChiP Nov 19 '14 at 05:34

1 Answers1

4

TArray is a dependant name, so you need to use typename like so:

typedef typename TArray::iterator iter;

This "should" (famous last words) work in MSVC also.

Here is a book I can remcommend that explains this pretty thoroughly:

C++ Templates: The Complete Guide

John Dibling
  • 99,718
  • 31
  • 186
  • 324
  • If I'm not mistaken, MSVC++ even accepts `typename` on some non-dependent names in templates. I don't think a diagnostic is required for that. – MSalters Nov 18 '14 at 13:58