C
Chris Swiedler
How do I limit a template parameter to a specific set of classes? If I
write code like
class MyStream1
{
public:
void Write(...) {}
};
class MyStream2
{
public:
void Write(...) {}
};
template <class S> S & operator<<(S &lhs, int rhs) { lhs.Write(rhs);
return lhs; }
MyStream1 ms1;
MyStream2 ms2;
ms1 << 5;
ms2 << 5;
std::cout << 5;
.... then the compiler complains that ostream doesn't have a Write
method, i.e. it's using my overloaded free operator<< to stream into
an ostream, which is obviously bad. I then tried:
class MyStream1
{
public:
typedef MyStream1 StreamType;
void Write(...) {}
};
class MyStream2
{
public:
typedef MyStream2 StreamType;
void Write(...) {}
};
template <class S> class S::StreamType & operator<< (class
S::StreamType &lhs, int rhs) { lhs.Write(rhs); return lhs;}
MyStream1 ms1;
MyStream2 ms2;
ms1 << 5;
ms2 << 5;
std::cout << 5;
When I do this, it no longer tries to use my overload for the ostream,
but instead complains that there is no valid overloaded operator<< for
MyStream1 or MyStream2. Is this nested typedef a valid way to limit my
overload to my own classes? Is there another way to do this?
I've actually switched away from this technique to using a base class
which implements Write(), and having the operator<< take the base
class as its first parameter. Still, I'm curious how I might
accomplish this.
chris
write code like
class MyStream1
{
public:
void Write(...) {}
};
class MyStream2
{
public:
void Write(...) {}
};
template <class S> S & operator<<(S &lhs, int rhs) { lhs.Write(rhs);
return lhs; }
MyStream1 ms1;
MyStream2 ms2;
ms1 << 5;
ms2 << 5;
std::cout << 5;
.... then the compiler complains that ostream doesn't have a Write
method, i.e. it's using my overloaded free operator<< to stream into
an ostream, which is obviously bad. I then tried:
class MyStream1
{
public:
typedef MyStream1 StreamType;
void Write(...) {}
};
class MyStream2
{
public:
typedef MyStream2 StreamType;
void Write(...) {}
};
template <class S> class S::StreamType & operator<< (class
S::StreamType &lhs, int rhs) { lhs.Write(rhs); return lhs;}
MyStream1 ms1;
MyStream2 ms2;
ms1 << 5;
ms2 << 5;
std::cout << 5;
When I do this, it no longer tries to use my overload for the ostream,
but instead complains that there is no valid overloaded operator<< for
MyStream1 or MyStream2. Is this nested typedef a valid way to limit my
overload to my own classes? Is there another way to do this?
I've actually switched away from this technique to using a base class
which implements Write(), and having the operator<< take the base
class as its first parameter. Still, I'm curious how I might
accomplish this.
chris