简体   繁体   English

在C ++中访问参数包的内部变量

[英]Accessing inner variables of parameter pack in C++

Is there any simple method for accessing inner members of whole parameter pack? 有没有简单的方法可以访问整个参数包的内部成员? Lets say you have following code 假设您有以下代码

#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;
}

I want proxy function to unpack member variables of plist and pass them to printer. 我希望代理函数解压缩plist的成员变量并将其传递给打印机。 Is there a simple way how to do this without iterating through parameter list? 有没有一种简单的方法而又无需遍历参数列表的方法?

After clearing several issues with your code, i could make it compile: 清除代码中的几个问题后,我可以对其进行编译:

  • A and B should be structs to make their definitions public. AB应该是公开其定义的结构。
  • there is no sense in forwarding their static members, just skip the forwarding - forwarding makes sense for "universal references" only 转发其静态成员没有任何意义,只是跳过转发-转发仅对“通用引用”有意义
  • In gcc, I had to put the one-argument printer before the variadic one 在gcc中,我不得不将单参数printer放在可变参数的printer之前

proxy now looks like this: 代理现在看起来像这样:

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...); 
}

And since the C 's are static constexpr members, you can just leave the argument pack: 而且由于C是静态constexpr成员,因此您只需保留参数pack:

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;
}

FYI, the correct call to std::forward would have looked like this, if C was an ordinary member variable of A and B: 仅供参考,如果C是A和B的普通成员变量,则对std::forward的正确调用应如下所示:

template <class ... TList>
std::ostream & proxy(std::ostream & out, TList&& ... plist) {
    return printer(out, std::forward<typename TList::type>(plist.C)...);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM