我所有的类都实现了dump
成员函数,例如:
struct A {
template <typename charT>
std::basic_ostream<charT> &
dump(std::basic_ostream<charT> &o) const {
return (o << x);
}
int x = 5;
};
我想为所有此类实现一次
operator<<
函数:template<typename charT, typename T>
std::basic_ostream<charT> &
operator<< (std::basic_ostream<charT> &o, const T &t) {
return t.dump(o);
}
问题在于此模板捕获了所有类型,包括标准类型。有没有办法解决这个问题?
最佳答案
template <typename T, typename charT>
auto operator<< (std::basic_ostream<charT> & str, const T & t) -> decltype(t.dump(str))
{
static_assert(std::is_same
<decltype(t.dump(str)),
std::basic_ostream<charT> &>::value,
".dump(ostream&) does not return ostream& !");
return t.dump(str);
}
这仅对定义了适当的
operator<<
成员的类型重载dump
。编辑:添加了static_assert以获得更好的消息。
关于c++ - 关于转储成员函数,operator <<函数的一般实现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34178478/