重新阅读您的问题后(由于此答案中的评论),我意识到您想要的不仅是转换为字符串(我在此处的另一个答案中的假设),而是转发到内部 ofstream。
现在,您想要实现的目标并不简单,而且在大多数情况下可能是矫枉过正。在[make_string][3]
我拥有的实现中(转发到 internal ostringstream
),我不允许传递操纵器。如果用户想要添加一个新行(我们在 linux 下开发),他们只需传递一个 '\n' 字符。
您的问题是转发操纵器(std::hex
,std::endl
...)。您的 operator<< 被定义为采用 T 类型的常量实例,但操纵器是函数指针,编译器无法将其与您的方法匹配。
操纵器是对std::basic_ostream
模板进行操作的函数。basic_ostream
模板和类ostream
定义为:
template <typename TChar, typename TTraits = char_traits<TChar> >
class basic_ostream;
typedef basic_ostream<char> ostream;
// or
// typedef basic_ostream<wchar_t> if using wide characters
那么可以传递给 std::ostream 的可能操纵器是:
typedef std::ostream& (*manip1)( std::ostream& );
typedef std::basic_ios< std::ostream::char_type, std::ostream::traits_type > ios_type;
typedef ios_type& (*manip2)( ios_type& );
typedef std::ios_base& (*manip3)( std::ios_base& );
如果您想接受操纵器,则必须在您的类中提供该重载:
class mystream
{
//...
public:
template <typename T>
mystream& operator<<( T datum ) {
stream << datum;
return *this
}
// overload for manipulators
mystream& operator<<( manip1 fp ) {
stream << fp;
return *this;
}
mystream& operator<<( manip2 fp ) {
stream << fp;
return *this;
}
mystream& operator<<( manip3 fp ) {
stream << fp;
return *this;
}
};
特别是, endl 的签名(可能是您唯一需要的)是:
template <typename Char, typename Traits>
std::basic_ostream<Char,Traits>&
std::endl( std::basic_ostream<Char,Traits>& stream );
所以它属于manip1
函数的类型。其他,例如std::hex
属于不同的类别(manip3
在这种特殊情况下)