gpt4 book ai didi

c++ - 将 std::tuple 的类型转换为 std::pair

转载 作者:行者123 更新时间:2023-11-30 02:21:39 25 4
gpt4 key购买 nike

Boost document向我们展示如何实现类型转换器

template<class A, template<class...> class B> struct mp_rename_impl;

template<template<class...> class A, class... T, template<class...> class B>
struct mp_rename_impl<A<T...>, B>
{
using type = B<T...>;
};

template<class A, template<class...> class B>
using mp_rename = typename mp_rename_impl<A, B>::type;

这个mp_rename的作用是将类型A转换为类型B。

示例:

mp_rename<std::pair<int, double>, std::tuple>

等于

std::tuple<int, double>

据我所知

mp_rename<std::pair<int, double>, std::tuple>

打电话

template<class A, template<class...> class B> struct mp_rename_impl;

之后转发到

template<template<class...> class A, class... T, template<class...> class B> struct mp_rename_impl<A<T...>, B>    

我的问题是,为什么编译器知道它应该转发给

template<template<class...> class A, class... T, template<class...> class B> struct mp_rename_impl<A<T...>, B>

并将A类拆分为

template<class...> class A, class... T

最佳答案

template<class A, template<class...> class B> struct mp_rename_impl;

template<template<class...> class A, class... T, template<class...> class B>
struct mp_rename_impl<A<T...>, B>
{
using type = B<T...>;
};

在这里mp_rename_impl<A<T...>, B>mp_rename_impl 的部分特化结构模板。

然后编译器使用partial ordering rules .即:

When a class template is instantiated, and there are partial specializations available, the compiler has to decide if the primary template is going to be used or one of its partial specializations.

1) If only one specialization matches the template arguments, that specialization is used

2) If more than one specialization matches, partial order rules are used to determine which specialization is more specialized. The most specialized specialization is used, if it is unique (if it is not unique, the program cannot be compiled)

3) If no specializations match, the primary template is used

因为你只有一个专业 mp_rename_impl<A<T...>, B>并且它与模板参数相匹配,然后由编译器选取。

编译器比较A<T...>反对std::pair<int, double>B反对std::tuple并推导出相应的类型:A作为std::pair , B作为std::tupleT...作为int, double .

关于c++ - 将 std::tuple 的类型转换为 std::pair,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48112507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com