why is overloading needed when using operator<< via template?
As in this question, I'm experimenting to stream via a class using SBRM/RAII, so
SBRM(x) << "test";
could do some extra's in the destructor, but my template knowledge seems to be limited.
What I have (made simpler for clarity) is:
#include <iostream>
#include <sstream>
class SBRM
{
public:
SBRM(int j) : i(j) {}
~SBRM() { std::cout << "SBRM(" << i << "): " << oss.str() << std::endl; }
template<typename T> SBRM& operator<<(T& in) { oss << in; return *this; }
// SBRM& operator<<(const long long& in) { oss << std::hex << "0x" << in; return *this; }
SBRM& operator<<(const double& in) { oss << in; return *this; }
SBRM& operator<<(const void* in) { oss << in; return *this; }
private:
int i;
std::ostringstream oss;
};
int main()
{
std::string ttt = "world";
const int i = 3;
SBRM(1) << "Hello";
SBRM(2) << ttt;
SBRM(3) << 0x1234567890123ll;
SBRM(4) << &i;
SBRM(5) << 5;
SBRM(6) << 0.23;
SBRM(7) << i;
SBRM(8) << 5 << ", " <&l开发者_如何学编程t; ttt << ", " << &i;
}
This sort of works:
SBRM(1): Hello
SBRM(2): world
SBRM(3): 3.20256e+14
SBRM(4): 0xbf8ee444
SBRM(5): 5
SBRM(6): 0.23
SBRM(7): 3
SBRM(8): 5, world, 0xbf8ee444
but my main concern is: why does the compiler require me to overload the template when using (non-string) literals?
Are there any tricks to avoid this or am I taking a wrong approach? Other suggestions are welcome because I now resorted to using a macro forNOT_QUITE_SBRM_MACRO(3, "At least, " << 5 << ", this works");
The issue is seen with gcc 4.1.2. and 4.4.3. Without the overloaded functions, I get:
sbrm-stream.cpp: In function ‘int main()’:
sbrm-stream.cpp:27: error: no match for ‘operator<<’ in ‘SBRM(3) << 320255973458211ll’
sbrm-stream.cpp:10: note: candidates are: SBRM& SBRM::operator<<(T&) [with T = long long int]
sbrm-stream.cpp:28: error: no match for ‘operator<<’ in ‘SBRM(4) << & i’
sbrm-stream.cpp:10: note: candidates are: SBRM& SBRM::operator<<(T&) [with T = const int*]
...
Because you’re expecting a non-const
argument and literals can never be treated as such. Make the argument const
and your troubles will go away:
template<typename T> SBRM& operator<<(T const& in) { oss << in; return *this; }
And as David has mentioned in his comment, you need overloads when using manipulators such as endl
. Here’s a shot at them:
SBRM& operator <<(std::ostream& (*manip)(std::ostream&)) {
oss << manip; // alternatively: manip(os);
return *this;
}
// same for:
ostream& operator <<(ios& (*manip)(ios&));
ostream& operator <<(ios_base& (*manip)(ios_base&));
This covers all the parameterless manipulators.
I’m not actually sure how the parametrized manipulators from <iomanip>
work but they seem to return a proxy object that can use the generic operator <<
variant.
精彩评论