It is currently Thu Feb 22, 2018 4:04 pm

All times are UTC - 5 hours

 Page 1 of 1 [ 1 post ] 
Author Message
 Post subject: Class Template With Variadic Constructor
PostPosted: Tue Feb 16, 2016 4:00 am 

Joined: Sat Aug 16, 2008 7:58 am
Posts: 452
I created a generic template class where the constructor can take [0,N] arguments and if 0 arguments are passed it will assign the first member in the vector to a nullptr; otherwise for each parameter passed in, it will be stored as a std::shared_ptr<T> inside of an std::vector<>. It also keeps track of how many elements are in the vector. Here is the class template:

#include <vector>
#include <memory>

template<typename T>
class Nodes {
    unsigned m_numParams;
    std::vector<std::shared_ptr<T>> m_vNodes;

    Nodes() : m_numParams(0), m_vNodes { nullptr } {}

    template <typename ... Ts >
    explicit Nodes( Ts&&...ts ) :
        m_numParams( sizeof...(Ts) ),
        m_vNodes{ std::make_shared<T>( std::forward<Ts>( ts ) )... }
}; // Nodes

And here it is in use.

int main() {
     int x = 3;
     int y = 5;
     int z = 7;

     Nodes<int> nodes( x, y, z );

     return 0;

I have not yet expanded this class to add or remove elements, to retrieve elements etc., but I may work on this later when I have more time. What I like about this class is that the constructor is designed to accept as many parameters as you pass into it when you may not know how many will be needed at the time of its call. I may also design the addNode() as a single, and an addNodes() in the same manner as the constructor. The same may go for removeNode() and removeNodes(). I thought that the general concept of this class may be useful for others to use so I posted it here.

Display posts from previous:  Sort by  
 Page 1 of 1 [ 1 post ] 

All times are UTC - 5 hours

Who is online

Users browsing this forum: No registered users and 1 guest

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Jump to: