C++ variadic template example
Kent - June 24, 2016
Complete example with variadic templates
This is the least viable and one of the most simple examples on how to use C++11 Variadic Templates. This sample has been tested with Microsoft Visual Studio 2015 and GCC 4.7.3.
The code is also available at Github
This example 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);
/*
Output should be:
SomeStruct()
SomeStruct(int a)
SomeStruct(const std::string & str)
SomeStruct(const std::string & str, int a)
*/
return 0;
}
See Also
- C++ Concepts: New keywords
- C++ std::sort predicate with templates
- C++ variadic templates
- Default explicit equality operator
- Mistakes
Comments
Any comments? Create a new discussion on GitHub.There used to be an inline comment form here, but it was removed.