C++11 : variadic templates(可变参数模板)

Introduction:

Before the possibilities of the new C++ language standardC++11, the use of templates was quite limited when it came to implementing for instance function objects (functors) & tuple facilities. Implementing these sort of things using earlier C++ standard often require similiar code to be repeated various times without forgetting preprocessor metaprogramming. However, thanks to variadic templates, programming new features using templates has become easierclearer & more memory-efficient.

Although the D programming language also provides the use of variadic templates, only variadic templates offered by C++11 standard will be covered here, so knowledge of D programming language‘s variadic templates is not required in order to read & understand this article. There are assumptions, however, that the reader of this article understands what class & function templates are & how to declare, define & use them.

 What is a variadic template?

Variadic template is a template, which can take an arbitrary number of template arguments of any type. Both the classes & functions can be variadic. Here‘s a variadic class template:

12
template<typename... Arguments>
class VariadicTemplate;
 

Any of the following ways to create an instance of this class template is valid:

123
VariadicTemplate<double, float> instance;
VariadicTemplate<bool, unsigned short int, long> instance;
VariadicTemplate<char, std::vector<int>, std::string, std::string, std::vector<long long>> instance;
 

The number of variadic template arguments can also be zero, so the following

VariadicTemplate<> instance;

is also valid C++11.

However, if you create a template like this:

12
template<typename T, typename... Arguments>
class VariadicTemplate;
 

You must set at least one type as a template argument (for typename T), unless default type has been initilialized, like in the following declaration:

12
template<typename T = int, typename... Arguments>
class VariadicTemplate;
 

 Syntax - the ellipsis operator (...):

The ellipsis operator (...) is an operator used in different contexts in C++. It‘s name comes from an ellipsis mechanism in C. In this mechanism programmer can create a function taking variable number of parameters. Probably the most famous function in both C & C++ to take advantage of this mechanism is printf-function in C standard library:

int printf (const char* format, ... );

Ellipsis mechanism can also be used with preprocessor in a form of a macro. A macro taking a variable number of parameters is called a variadic macro.

#define VARIADIC_MACRO(...) 

In C++, this ellipsis operator got a new meaning in different context called exception handling. The operator is used in catch blocks after try blocks:

123456
try{
    // Try block.
}
catch(...){
    // Catch block.
}
 

Here, the ellipsis operator indicates that the catch block takes in any exception thrown from the try block as it‘s parameter, no matter the type.

In C++11, variadic templates brought yet another meaning for this operator. The operator works somewhat like in ellipsis mechanism as already stated, but it‘s bit more complex:

12
template<typename... Arguments>
void SampleFunction(Arguments... parameters);
 

Here‘s a function template. The contents of the variadic template arguments are called parameter packs. These packs will then be unpacked inside the function parameters. For example, if you create a function call to the previous variadic function template...

SampleFunction<intint>(16, 24);

...an equivalent function template would be like this:

12
template<typename T, typename U>
void SampleFunction(T param1, U param2);
 

 Syntax - the sizeof... operator (sizeof...):

Another operator used with variadic templates is the sizeof...-operator. Unlike the sizeof operator, which can be used to determine the size of a type (for example sizeof(int) or sizeof(double)), sizeof... operator can be used to determine the amount of types given into a variadic template. This can be achieved like this:

12345
template<typename... Arguments>
class VariadicTemplate{
private:
    static const unsigned short int size = sizeof...(Arguments);
};
 

 Syntax - two ellipsis operators together (......):

In some circumstances, there can be two ellipsis operators put together (......). These two operators can also be separated (written as ... ...).

Probably the most clear way, however, is to separate these two operators with a comma (..., ...). Both ways with a comma or without a comma are acceptable.

This kind of syntax can appear with variadic function templates using ellipsis mechanism:

1234
template<typename... Arguments>
void SampleFunction(Arguments......){

}
 

As already stated, these two ellipsis operator put together can be written differently, so the following examples

1234
template<typename... Arguments>
void SampleFunction(Arguments... ...){

}
 
1234
template<typename... Arguments>
void SampleFunction(Arguments..., ...){

}
 

work as well.

 Author‘s opinions & thoughts: For the sake of readability, use the last method to mark the two following ellipsis operators. The previous alternatives may be found confusing and/or cumbersome. Some may find it a matter of taste, though.

 Uses of variadic templates - inheritance & initialization lists:

When it comes to classes, variadic templates can be used with inheritance & initialization lists. Inheritance taking advantage of variadic templates can be accomplished like this:

12
template<typename... BaseClasses>
class VariadicTemplate : public BaseClasses...
 

And, if we want to create a constructor inside this class using initialization list to call the constructors of all the given base classes as template arguments, we‘d have to do it this way:

1234567
template<typename... BaseClasses>
class VariadicTemplate : public BaseClasses...{
public:
    VariadicTemplate(BaseClasses&&... base_classes) : BaseClasses(base_classes)...{

    }
};
 

As you can see there‘s a new operator introduced in C++11 in the constructor‘s parameter list - an rvalue operator (&&), which allows rvalue references. This article is not intended to cover the use of this operator, but for information how to use this operator (& rvalue references in general), please follow this link:
http://thbecker.net/articles/rvalue_references/section_01.html

 Uses of variadic templates - variadic class template specialization:

Like class templates, variadic class templates can also be specialized. With templates, the specialization happens like this:

123456789101112131415
template<typename T>
class Template{
public:
    void SampleFunction(T param){

    }
};

template<>
class Template<int>{
public:
    void SampleFunction(int param){

    }
};
 

But with variadic templates it‘s like the following:

123456789101112131415
template<typename... Arguments>
class VariadicTemplate{
public:
    void SampleFunction(Arguments... params){

    }
};

template<>
class VariadicTemplate<double, int, long>{
public:
    void SampleFunction(double param1, int param2, long param3){

    }
};
 

 Caution: Some compilers may not support variadic class template specialization yet, or their implementation may be somewhat incomplete.

 See also:

If you are interested in seeing a C++11 standard class template utilizing variadic templates, please take a look at already mentioned tuple from the link below:
http://www.cplusplus.com/reference/std/tuple/tuple/

Another field where variadic templates may come in handy is delegates. If you are already familiar with managed C++ and/or C#, picking up C++ delegates may not be a problem. You might find good use for them in C++ anyway.

时间: 2024-08-29 18:50:41

C++11 : variadic templates(可变参数模板)的相关文章

c++11可变参数模板的使用1

1.概述 C++11的新特性--可变模版参数(variadic templates)是C++11新增的最强大的特性之一,它对参数进行了高度泛化,它能表示0到任意个数.任意类型的参数.相比C++98/03,类模版和函数模版中只能含固定数量的模版参数,可变模版参数无疑是一个巨大的改进.然而由于可变模版参数比较抽象,使用起来需要一定的技巧,所以它也是C++11中最难理解和掌握的特性之一. 虽然掌握可变模版参数有一定难度,但是它却是C++11中最有意思的一个特性,本文希望带领读者由浅入深的认识和掌握这一

C++ 11 可变参数模板和 boost::any 实现可变参数函数

1 class SqlHelper 2 { 3 public: 4 template <typename... Params> 5 static bool preparedExecute(sql::PreparedStatement* pstmt, Params... parameters) 6 { 7 return doPreparedExecute(pstmt, 1, parameters...); 8 } 9 10 private: 11 template <typename...

c++11 可变参数模板函数

c++11 可变参数模板函数 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <vector> #include <map> // 在C++11之前,类模板和函数模板只能含有固定数量的模板参数.C++11增强了模板功能,允许模板定义中包含0到任意个模板参数,这就是可变参数模板. // 可变参数模板和普通模板的语义是一样的,只是写法上稍有区别,声明可变

第21课 可变参数模板(2)_展开参数包

1. 可变参数模板函数 (1)递归函数方式展开参数包 ①一般需要提供前向声明.一个参数包的展开函数和一个递归终止函数. ②前向声明有时可省略,递归终止函数可以是0个或n个参数 (2)逗号表达式和初始化列表方式展开参数包 ①逗号表达式按顺序执行,返回最后一个表达式的值. ②initilizer_list可接受任意多个不同类型的参数. ③借助逗号表达式来展开包,并将返回的结果用于初始化initilizer_list. [编程实验]展开可变参数模板函数的参数包 #include <iostream>

C++反射机制:可变参数模板实现C++反射

1. 概要   本文描述一个通过C++可变参数模板实现C++反射机制的方法.该方法非常实用,在Nebula高性能网络框架中大量应用,实现了非常强大的动态加载动态创建功能.Nebula框架在coding.net的仓库地址.   C++11的新特性--可变模版参数(variadic templates)是C++11新增的最强大的特性之一,它对参数进行了高度泛化,它能表示0到任意个数.任意类型的参数.关于可变参数模板的原理和应用不是本文重点,不过通过本文中的例子也可充分了解可变参数模板是如何应用的.

格式工厂(三) Variadic Templates

版权声明:本文为博主原创文章,未经博主允许不得转载. 这次主要介绍C++11的又一个新特性 Variadic Templates (可变模板参数) 它的实现类似于initializer_list<>,它可是使类模板接受一包参数 本节主要应用递归的形式介绍 Variadic  Templates 1.简单的调用 #include <iostream> #include "string" using namespace std; void printX() {}//

可变参数模板用法

//可变参数模板 //可变参数模板,可以创建可接受可变数量参数的模板函数和模板类 //本程序通过模板函数来实例一下可变参数模板的基本用法 #include<iostream> using namespace std; void one(){}//当最后一个参数传完后,需要一个无参的重载版本 template <typename T>//当只剩最后一个参数时,编译器优先选择此模板,这样最后一个输出后面就没有逗号了 void one(T v) { cout << v <

C++的可变参数模板函数

可变参数模板函数写法: 模板参数里写typename... args,表明args是一个可变参数. 之后再函数参数里args后面也要加...,以表示该参数为可变参数. 函数参数中对于args的修饰,会扩展到所有该args的参数,比如下面代码: //可变参数模板函数使用方法1:递归调用,每次将可变参数规模变小直到为0 template<typename T> void print(const T& x) { cout << "最后一次调用print,输出:"

C++11 可变参数模板构造string列表

#include <iostream> #include <cstdint> #include <list> #include <string> template<typename T> typename std::enable_if<std::is_integral<T>::value, std::string>::type to_string(const T & val) { return std::to_st