Reputation: 3418
I'm trying to show off variety on a piece of course work and hoped to use the << operator to easily add variables to a list. Eg:
UpdateList<string> test;
test << "one" << "two" << "three";
My problem, is that EVERY SINGLE example of the << operator is to do with ostream.
My current attempt is:
template <class T> class UpdateList
{
...ect...
UpdateList<T>& operator <<(T &value)
{
return out;
}
}
Does anyone know how I can achieve this, or is it actually not possible inside C++?
Upvotes: 0
Views: 104
Reputation: 1
You' ll need an overloaded operator<<()
outside the class:
template<typename T>
UpdateList<T>& operator<<(UpdateList<T>& out, const T& value)
{
return out;
}
Upvotes: 1
Reputation: 15870
You would (typically) want to declare it as a non-class member:
template<typename T>
UpdateList<T>& operator<<(UpdateList<T>& lst, const T& value)
{
lst.add(value); // whatever your add/insert method is goes here
return lst;
}
Upvotes: 1
Reputation: 55897
You should use const T& value
.
Following fragment of code should work fine
UpdateList<T>& operator << (const T& value)
{
// push to list
return *this;
}
or
UpdateList<T>& operator << (T value)
{
// push to list
return *this;
}
in C++11 (thanks to rightfold)
Upvotes: 6