问题描述
如何为特定的operator<<
模板实例创建std::tuple<double,int,int>
?
using FST = std::tuple<double,int>;
std::string TupleAsstr(const FST & i) {
return "(" +
std::to_string(std::get<0>(i)) + "," +
std::to_string(std::get<1>(i)) + "," +
std::to_string(std::get<2>(i)) +
")";
}
// what I have
FST const& fst = std::make_tuple(1.0,4,5);
std::cout << TupleAsstr(fst) << std::endl;
// what I want
std::cout << fst << std::endl;
仅针对此特定情况,我不需要针对N类型的通用解决方案。
解决方法
您可以将operator<<
类型的FST
重载。另外,最好也将FST
类型放入命名空间,以免与现有的重载冲突:
namespace my {
using FST = std::tuple<double,int,int>;
std::ostream& operator<<(std::ostream &out,const my::FST & i) {
return out << "(" <<
std::to_string(std::get<0>(i)) << "," <<
std::to_string(std::get<1>(i)) << "," <<
std::to_string(std::get<2>(i)) <<
")";
}
}
然后在要使用它时执行using my::operator<<
。
这里是demo。