[英]printing class object using variadic templates
I am trying to understand folding and variadic templates.我正在尝试了解折叠和可变参数模板。 I designed a very naive Tuple class.我设计了一个非常幼稚的元组 class。 I can create a tuple object, but I would like to print the object.我可以创建一个元组 object,但我想打印 object。 It seems odd that this problem hasn't been touched almost anywhere (at least I haven't found any resource so far. This is the code这个问题几乎没有在任何地方被触及,这似乎很奇怪(至少到目前为止我还没有找到任何资源。这是代码
#include <iostream>
#include <string>
// this is the implementation of my own tuple using variadic templates
template <class... T>
class Tuple {};
template <class T, class... Args>
class Tuple<T, Args...> {
private:
T first;
Tuple<Args...> rest;
public:
// friends
friend std::ostream& operator<<(std::ostream& out, const Tuple<T, Args...>& tuply);
public:
Tuple(T&& firsty, Args&&... resty): first(firsty), rest(resty...){};
};
template <class T, class Args...>
std::ostream& operator<<(std::ostream& out, const Tuple<T, Args...>& tuply){
out << tuply.first;
((out << " - " << std::forward<Args>(tuply.rest)), ...);
}
probably Tuple<T, Args...>
is illegal, and the line where I am using folding does not make sense.可能Tuple<T, Args...>
是非法的,并且我使用折叠的行没有意义。 I really cannot find a way to make this work.我真的无法找到一种方法来完成这项工作。 Can someone help?有人可以帮忙吗?
Just use recursion:只需使用递归:
// this is the implementation of my own tuple using variadic templates
template<class... T>
class Tuple {};
template<class T, class... Args>
class Tuple<T, Args...> {
private:
T first;
Tuple<Args...> rest;
friend std::ostream& operator<<(std::ostream& out, const Tuple& tuply) {
out << tuply.first;
if constexpr (sizeof...(Args) == 0) return out;
else return out << " - " << tuply.rest;
}
public:
Tuple(T&& firsty, Args&&... resty)
: first(std::forward<T>(firsty)), rest(std::forward<Args>(resty)...) { }
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.