When writing a class to work in a shell around an object allocated by a bunch, I ran into a problem with implicit type conversion, which can be reduced to this simple example.
In the code below, the shell class manages the heaped object and is implicitly converted to a reference to this object. This allows you to pass a wrapper object as an argument to the write (...) function, since an implicit conversion occurs.
However, when trying to allow a call to the <<(...) operator, the compiler does not work if an explicit conversion is not performed (verified using the MSVC8.0, Intel 9.1, and gcc 4.2.1 compilers).
So, (1) why does implicit conversion fail in this case? (2) could this be related to the search argument dependent? and (3) is there anything that can be done to make this work without an explicit cast?
template <typename T>
class wrapper
{
T* t;
public:
explicit wrapper(T * const p) : t(p) { }
~wrapper() { delete t; }
operator T & () const { return *t; }
};
void write(std::ostream& os)
{
os << "(1) Hello, world!\n";
}
int main()
{
wrapper<std::ostream> file(new std::ofstream("test.txt"));
write(file);
static_cast<std::ostream&>( file ) << "(2) Hello, world!\n";
}
source
share