本文介绍了操作符<<函数的转储成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的所有类都实现了一个 dump
成员函数,例如:
struct A {
template< typename charT>
std :: basic_ostream< charT> &
dump(std :: basic_ostream< charT>& o)const {
return(o<< x);
}
int x = 5;
};
我想实现运算符<< $ c $对于所有这样的类,c>函数一次:
template< typename charT,typename T>
std :: basic_ostream< charT> &
operator<< (std :: basic_ostream< charT>& o,const T& t){
return t.dump(o);
}
问题是所有类型都被此模板捕获,包括标准类型。有没有办法解决这个问题?
解决方案
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);
}
这会重载运算符<<
仅适用于定义适当的转储
成员的类型。
编辑:添加static_assert以获得更好的消息。 / p>
All my classes implement a dump
member function, e.g.:
struct A {
template <typename charT>
std::basic_ostream<charT> &
dump(std::basic_ostream<charT> &o) const {
return (o << x);
}
int x = 5;
};
I would like to implement an operator<<
function once for all such classes:
template<typename charT, typename T>
std::basic_ostream<charT> &
operator<< (std::basic_ostream<charT> &o, const T &t) {
return t.dump(o);
}
The problem is that all types are caught by this template, including the standard types. Is there a way to get around this problem?
解决方案
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);
}
This overloads operator<<
only for types that define an appropriate dump
member.
Edit: added static_assert for better messages.
这篇关于操作符<<函数的转储成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!