Please take note of the updates at the end of this post.
Update: I have created a public project on GitHub for this library!
I would like to have a single template that once and for all takes care of pretty-printing all STL containers via operator<<. In pseudo code, I'm looking for something like this:
template<container C, class T, String delim = ", ", String open = "[", String close = "]">
std::ostream & operator<<(std::ostream & o, const C<T> …Run Code Online (Sandbox Code Playgroud) 如何迭代元组(使用C++ 11)?我尝试了以下方法:
for(int i=0; i<std::tuple_size<T...>::value; ++i)
std::get<i>(my_tuple).do_sth();
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
错误1:抱歉,未实现:无法将"Listener ..."扩展为固定长度的参数列表.
错误2:我不能出现在常量表达式中.
那么,我如何正确迭代元组的元素?
这是我之前关于漂亮印刷STL容器的问题的后续行动,为此我们设法开发了一个非常优雅且完全通用的解决方案.
在下一步中,我想std::tuple<Args...>使用可变参数模板包含漂亮打印(因此这是严格的C++ 11).因为std::pair<S,T>,我只是说
std::ostream & operator<<(std::ostream & o, const std::pair<S,T> & p)
{
return o << "(" << p.first << ", " << p.second << ")";
}
Run Code Online (Sandbox Code Playgroud)
打印元组的类似结构是什么?
我已经尝试了各种模板参数堆栈解包,传递索引并使用SFINAE来发现我何时处于最后一个元素,但没有成功.我不会用破碎的代码给你带来负担; 问题描述有希望直截了当.基本上,我想要以下行为:
auto a = std::make_tuple(5, "Hello", -0.1);
std::cout << a << std::endl; // prints: (5, "Hello", -0.1)
Run Code Online (Sandbox Code Playgroud)
与前一个问题包含相同级别的通用性(char/wchar_t,pair delimiters)的加分点!
以下内容不会为我编译.我没有想法......有什么帮助吗?
template<>
inline
std::ostream& operator<< <const std::map<std::string, std::string> > (std::ostream& stream, const std::map<std::string, std::string>& some_map)
{
return stream;
}
Run Code Online (Sandbox Code Playgroud)
g ++给了我以下错误:
错误:在'<'标记之前的预期初始化程序
编辑:1 好的,因为每个人都告诉我超载,让我举一个对重载没有意义的例子.如果我有这个怎么办:
template <typename T>
inline
std::ostream& operator<<(std::ostream& stream, const T& something)
{
stream << something.toString();
return stream;
}
class Foo
{
public:
Foo(std::string s)
{
name = s;
}
std::string toString() const
{
return name;
}
private:
std::string name;
};
class Bar
{
public:
Bar(int i)
{
val = i;
}
std::string toString() const
{
std::ostringstream stream; …Run Code Online (Sandbox Code Playgroud)