The following program does not compile. Apparantly "t" is inaccessible.
#include <iostream>
using namespace std;
template <class T> class Foo
{
T t;
public:
Foo(T t_) : t(t_) { }
void print() const { cout << t << endl; }
friend Foo<T> operator+(int n, const Foo<T> &f);
};
template <class T>
Foo<T> operator+(int n, const Foo<T> &f)
{
return Foo<T>(n + f.t);
}
int main()
{
Foo<int> f1(3), f2(5);
(1 + f2).print();
return 0;
}
This one does compile.
#include <iostream>
using namespace std;
template <class T> class Foo
{
public:
T t;
Foo(T t_) : t(t_) { }
void print() const { cout << t << endl; }
};
template <class T>
Foo<T> operator+(int n, const Foo<T> &f)
{
return Foo<T>(n + f.t);
}
int main()
{
Foo<int> f1(3), f2(5);
(1 + f2).print();
return 0;
}
And so does this one.
#include <iostream>
using namespace std;
template <class T> class Foo
{
T t;
public:
Foo(T t_) : t(t_) { }
void print() const { cout << t << endl; }
friend Foo<T> operator+(int n, const Foo<T> &f);
};
Foo<int> operator+(int n, const Foo<int> &f)
{
return Foo<int>(n + f.t);
}
int main()
{
Foo<int> f1(3), f2(5);
(1 + f2).print();
return 0;
}
Strange huh? Can someone please explain why the first program doesn't
compile? I can rewrite it into an equivalent version that does compile but I
am curious as to why that version does not. I am using VC++ 6.0. Thanks.