Originally Posted by
anon
Here's some reading.
I'd take the last bit of advice (implementing the friend operator within the class) especially seeing that with templates you won't be able to separate the implementation from the declarations anyway.
The way I did it wasn't mentioned in the article. Is it one of the other ways of the "several ways to do this"?
I've encountered yet another situation where one compiler will compile and the other does not.
This code is pure copy and paste off of the given link.
Code:
#include <iostream>
template<typename T> class Foo; // pre-declare the template class itself
template<typename T> Foo<T> operator+ (const Foo<T>& lhs, const Foo<T>& rhs);
template<typename T> std::ostream& operator<< (std::ostream& o, const Foo<T>& x);
template<typename T>
class Foo {
public:
Foo(const T& value = T());
friend Foo<T> operator+ <>(const Foo<T>& lhs, const Foo<T>& rhs);
friend std::ostream& operator<< <>(std::ostream& o, const Foo<T>& x);
private:
T value_;
};
int main()
{
Foo<int> lhs(1);
Foo<int> rhs(2);
Foo<int> result = lhs + rhs;
std::cout << result;
}
template<typename T>
Foo<T>::Foo(const T& value = T())
: value_(value)
{ }
template<typename T>
Foo<T> operator+ (const Foo<T>& lhs, const Foo<T>& rhs)
{ return Foo<T>(lhs.value_ + rhs.value_); }
template<typename T>
std::ostream& operator<< (std::ostream& o, const Foo<T>& x)
{ return o << x.value_; }
Visual Studio compiles happily and g++ gives the following errors:
Code:
t8.cpp:28: error: default argument given for parameter 1 of `Foo<T>::Foo(const T&)'
t8.cpp:10: error: after previous specification in `Foo<T>::Foo(const T&)'
So, which should it be? Is this even more proof of the inferiority of Microsoft's compiler?