Is it possible to create a completely arbitrary private member tuple in a C++11 variadic class constructor?

大兔子大兔子 提交于 2019-12-13 05:50:22

问题


My apologies if this has been asked before - searched with no definite answer, and I'm beginning to wonder if it is even possible. I am trying to learn C++11 and have run into trouble with variadic templates. I think I grasp (finally) the concept of variadic function parameters, and why/how recursion is used to unwrap and process them, but am having trouble with a (I think) similar concept in class constructors.

Suppose I want to create a variadic template class that has a mixed-type container (assume tuple) as a private member. Is it possible to push an arbitrary number of variously-typed objects into that tuple when the class object is constructed? Something like:

#include <tuple>

// forward declaration - is this needed?
template <class ... args>
class myClass;

template <class H, class ... T>
class myClass <H, T ...>
{
 private:
     std::tuple<anything can go here> mycontainer;
 public:
     myClass(const H& head, const T& ... tail)
     {
            push head into mycontainer;
            do some sort of recursion with tail;
     }
}

I've been screwing around with std::tuple_cat and std::make_tuple and thought that I was on to something for a while, but no luck.

It has been a long time since I've had anything to do with C++, so my apologies if I'm totally off my nut. I just started looking at this after doing some reading about the C++11 features.

EDIT: Just adding that I'm on GCC 4.8.x and/or Visual Studio 2012


回答1:


Yes, it's possible to construct a member from some of those variadic types. For example:

template <class ... T>
class myClass {
  std::tuple<T...> mytuple;
public:
  // Constructor that takes const refs to the Ts and constructs tuple:
  myclass(const T&... args) : mytuple(args...) {}

  // Perfect forwarding constructor that will try to construct tuple
  // from arbitrary lvalue/rvalue parameters:
  template <class... Args>
  myclass(Args&&... args) : mytuple(std::forward<Args>(args)...) {}
};

If you're asking for something more specific, you'll have to describe it in more detail.



来源:https://stackoverflow.com/questions/17737146/is-it-possible-to-create-a-completely-arbitrary-private-member-tuple-in-a-c11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!