C++ variadic template example

By , last updated November 14, 2019

This is the least viable and one of the most simple examples on how to use C++11 Variadic Templates. You should understand it well after reading C++ variadic templates tutorial.

This sample has been tested with Microsoft Visual Studio 2015 and GCC 4.7.3.

The code will use perfect forwarding with variadic templates to create a class wrapper around a structure, which again call the correct constructors in the structure.

//=================================================================
//  VariadicTemplate.cpp:
//=================================================================

#include <iostream>
#include <memory>
#include <type_traits>

struct SomeStruct
{
    SomeStruct()
    {
        std::cout << "SomeStruct()\n";
    }

    SomeStruct(int a)
    {
        std::cout << "SomeStruct(int a)\n";
    }

    SomeStruct(const std::string & str)
    {
        std::cout << "SomeStruct(const std::string & str)\n";
    }

    SomeStruct(const std::string & str, int a)
    {
        std::cout << 
            "SomeStruct(const std::string & str, int a)\n";
    }

};


template<typename T>
class ClassWrapper
{
    public:
        typedef T                   type;
        typedef std::unique_ptr<T>  type_ptr;
        typedef ClassWrapper<T>     this_type;

    public:
        template<typename ... Args>
        static type_ptr Create(Args&&...args)
        {
            return type_ptr(
                new T(std::forward<Args>(args)...)
            );
        }

};

int main(int args, char ** argv, char ** arge)
{
    // Create a typedef to safe typing
    typedef ClassWrapper<SomeStruct>    CWSS;

    // Exercise the different SomeStruct 
    // constructors (ctor) through ClassWrapper  
    auto p1 = CWSS::Create();
    auto p2 = CWSS::Create(123);
    auto p3 = CWSS::Create("string");
    auto p4 = CWSS::Create("string", 234);

    

    return 0;
}

Output should be:

SomeStruct()
SomeStruct(int a)
SomeStruct(const std::string & str)
SomeStruct(const std::string & str, int a)

The code is also available at Github

Professional Software Developer, doing mostly C++. Connect with Kent on Twitter.