我有一组模板/函数,允许我打印元组/对,假设元组/对中的每种类型都有operator<<
为其定义的。不幸的是,由于 17.4.3.1,添加我的内容是非法的operator<<
重载到std
。有没有其他方法可以让 ADL 找到我的operator<<
?如果没有,将我的超载包裹起来有什么实际危害吗?namespace std{}
?
任何感兴趣的人的代码:(我正在使用 gcc-4.5)
namespace tuples {
using ::std::tuple;
using ::std::make_tuple;
using ::std::get;
namespace detail {
template< typename...args >
size_t size( tuple<args...> const& )
{
return sizeof...(args);
};
template<size_t N>
struct for_each_ri_impl
{
template<typename Func, typename Tuple>
void operator()(Func func, Tuple const& arg)
{
for_each_ri_impl<N-1>()(func, arg );
func( get<N>( arg ), size(arg) - N - 1 );
}
};
template<>
struct for_each_ri_impl<0>
{
template<typename Func, typename Tuple>
void operator()(Func func, Tuple const& arg)
{
func( get<0>( arg ), size(arg) - 1 );
}
};
}//detail
template<typename Func, typename ... Args>
void for_each_ri( tuple<Args...>const& tup, Func func )
{
detail::for_each_ri_impl< sizeof...(Args)-1>()( func, tup );
}
struct printer {
std::ostream& out;
const std::string& str;
explicit printer( std::ostream& out=std::cout, std::string const& str="," ) : out(out), str(str) { }
template<typename T>void operator()(T const&t, size_t i=-1) const { out<<t; if(i) out<<str; }
};
//Should this next line go into namespace std? Is there another way?
template<typename ... Args>
std::ostream& operator<<(std::ostream& out, std::tuple< Args... > const& tup)
{
out << '[';
tuples::for_each_ri( tup, tuples::printer(out,", ") );
return out << ']';
}
} //tuples
//Edits --
int main()
{
using namespace std;
cout<<make_tuple(1,'a',"Hello")<<endl;
return 0;
}
编译以上结果:
test.cpp:在函数“int main()”中:
test.cpp:69:31:错误:无法将 'std::ostream' 左值绑定到 'std::basic_ostream&&' > /opt/local/include/gcc45/c++/ostream:579:5:错误:初始化参数 1 'std::basic_ostream<_chart _traits>& std::operator&&, const _Tp&) [其中 _CharT = char, _Traits = std::char_traits, _Tp = std::元组]'