0

I have a pretty simple template which is a container which is an array of T. I am getting a syntax error :

container.h(7): error C2143: syntax error : missing ';' before '&'. I have tried removing the declaration there but then the error just skips over to the definition. Would appreciate any help.

EDIT: now i fixed the using namespace thing, but another error popped: container.h(8): error C2975: 'Container' : invalid template argument for 'unnamed-parameter', expected compile-time constant expression

#include <typeinfo.h>
#include <assert.h>
#include <iostream>
#pragma once

using namespace std; 
template <typename T, int> class Container;
template <typename T, int> ostream& operator<< <>(ostream &, const Container<T,int> &);

template<class T , int capacity=0> class Container
{
    //using namespace std;
private:
    T inside[capacity];
public:
    Container()
    {

    }

    ~Container(void)
    {
    }

    void set(const T &tType, int index)
    {
        assert(index>=0 && index<= capacity);
        inside[index] = tType;
    }

    T& operator[](int index)
    {
        assert(index>=0 && index<= capacity);
        return inside[index];
    }

    friend ostream& operator<< <>(ostream& out, const Container<T,int> c);
    {
        for(int i=0;i<sizeof(inside)/sizeof(T);i++)
            out<<c.inside[i]<< "\t";
        return out;
    }
};
Or Cyngiser
  • 1,027
  • 1
  • 12
  • 16
  • Also write the ostream `operator<<` overload inside the class with a `friend` specifier, its better and the forward declaration is not needed. – Manu343726 Sep 11 '13 at 12:09
  • 2
    After your edit you are still left with the problem I pointer out in my answer: `Container` is not valid, you need `Container`. – Daniel Frey Sep 11 '13 at 12:13

2 Answers2

4

You probably want:

template <typename T, int N>
ostream& operator<<(ostream &, const Container<T,N> &);
//                                               ^ here you need N, not int!

or, since you don't actually need the forward declaration, you can simply use this implementation in your class:

friend ostream& operator<<(ostream & out, const Container<T,capacity>& c)
{
    for(int i=0;i<capacity;++i)
        out<<c.inside[i]<< "\t";
    return out;
}
Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
0

You want something like:

template <typename T, int N>
friend ostream& operator<<(ostream & out, const Container<T,N>& c) {
    for(int i=0;i<sizeof(inside)/sizeof(T);i++)
        out<<c.inside[i]<< "\t";
    return out;
}
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • this code works, but please briefly explain why I need to repeat that template<...> thing if I am already inside a templated class? much appreciation. – Or Cyngiser Sep 11 '13 at 12:18
  • @OrCyngiser Because a `friend` function defined inside a class is not part of the class. – Oktalist Sep 11 '13 at 15:05