Hiding C++ template parameter packs in a tuple

栏目: IT技术 · 发布时间: 3年前

内容简介:May 29th, 2020C++11 introduced variadic templates and template parameter packs.Passing template parameter packs around is a bit of a hassle, because the dots “soak up” parameters, which make them hard to pass to other templated types. You also can’t “save”
Hiding C++ template parameter packs in a tuple

Raymond

May 29th, 2020

C++11 introduced variadic templates and template parameter packs.

template<typename... Args>
struct S;

Passing template parameter packs around is a bit of a hassle, because the dots “soak up” parameters, which make them hard to pass to other templated types. You also can’t “save” parameter packs in another type:

template<typename... Args>
struct S
{
    // doesn't compile: cannot create a type that
    // is itself a parameter pack
    using TheArgs = Args...;
};

One workaround for this is to capture the types into a std::tuple .

template<typename... Args>
struct S
{
    using Tuple = std::tuple<Args...>;
};

You can then pass the Tuple around, and if you need to extract the types, you can pull them out of the tuple.

My first thought about how to extract the types was to use std::get :

// code in italics is wrong
template<typename... Args>
struct Traits
{
    using Tuple = std::tuple<Args...>;
    static constexpr auto Size = sizeof...(Args);
    template <std::size_t N>
    <i>using Nth = decltype(std::get<N>(std::declval<Tuple>()));</i>
    using First = Nth<0>;
    using Last  = Nth<Size - 1>
};

This doesn’t work because std::get returns a reference:

void f()
{
 whatis<Traits<int, double>::First>();
}

    call    void whatis<int&&>()

This behavior is presumably so you can modify the tuple:

std::tuple<int> tuple;
std::get<0>(tuple) = 2;

Fortunately, there’s another way to extract the type from a tuple: std::tuple_element .

template<typename... Args>
struct Traits
{
    using Tuple = std::tuple<Args...>;
    template <std::size_t N>
    using Nth = typename std::tuple_element<N, Tuple>::type;
    using First = Nth<0>;
    using Last  = Nth<Size - 1>
};

This provides a simpler way to extract the last type from a template parameter pack than writing some horrible recursive template metaprogram, which is what some people did instead of hiding the pack inside a tuple.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

高等应用数学问题的MATLAB求解

高等应用数学问题的MATLAB求解

薛定宇、陈阳泉 / 清华大学出版社 / 2008-10 / 49.00元

薛定宇和陈阳泉编著的《高等应用数学问题的MATLAB求解》首先介绍了MATLAB语言程序设计的基本内容,在此基础上系统介绍了各个应用数学领域的问题求解,如基于MATLAB的微积分问题、线性代数问题的计算机求解、积分变换和复变函数问题、非线性方程与最优化问题、常微分方程与偏微分方程问题、数据插值与函数逼近问题、概率论与数理统计问题的解析解和数值解法等,还介绍了较新的非传统方法,如模糊逻辑与模糊推理、......一起来看看 《高等应用数学问题的MATLAB求解》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具