简体   繁体   中英

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. 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.
  • 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

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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