是否有任何简单的方法可以访问整个参数包的内部成员?假设您有以下代码
#include <iostream>
class A {
typedef int type;
constexpr static type C = 5;
};
class B {
typedef unsigned type;
constexpr static type C = 6;
};
template <class T1, class ... TList>
std::ostream & printer(std::ostream & out, T1 t1, TList ... plist) {
out << t1 << " ";
return printer(out, plist...);
}
template <class T1>
std::ostream & printer(std::ostream & out, T1 t1) {
return out << t1 << std::endl;
}
template <class ... TList>
std::ostream & proxy(std::ostream & out, TList ... plist) {
return printer(out, std::forward<TList::type ...>(plist::C ...));
}
int main(int argc, const char * argv[])
{
proxy(std::cout, A(), B());
return 0;
}
我希望代理函数解压缩plist的成员变量并将它们传递给打印机。有没有一种简单的方法可以在不重复参数列表的情况下完成这项工作?
答案 0 :(得分:2)
在清除了代码的几个问题后,我可以编译:
A
和B
应该是结构化的公开。printer
放在可变参数之前代理现在看起来像这样:
template <class ... TList>
std::ostream & proxy(std::ostream & out, TList ... plist) {
//leave the forward, plist is a variable pack, so operator.
return printer(out, plist.C ...);
//or:
return printer(out, TList::C...);
}
由于C
是静态的constexpr成员,你可以离开参数包:
template <class ... TList>
std::ostream & proxy(std::ostream & out) {
return printer(out, TList::C ...);
}
int main(int argc, const char * argv[])
{
proxy<A,B>(std::cout);
return 0;
}
仅供参考,如果std::forward
是A和B的普通成员变量,对C
的正确调用将如下所示:
template <class ... TList>
std::ostream & proxy(std::ostream & out, TList&& ... plist) {
return printer(out, std::forward<typename TList::type>(plist.C)...);
}