std :: common_type实现 [英] std::common_type implementation

查看:132
本文介绍了std :: common_type实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了看看它是如何工作的,我看看 type_traits std :: common_type 的libstdc ++实现>。我不得不承认,我不真的明白它是如何工作的。这是:

Just to see how it worked, I looked at the libstdc++ implementation of std::common_type in the header type_traits. I have to admit that I don't really understand how it works. Here it is:

/// common_type
template<typename... _Tp>
    struct common_type;

template<typename _Tp>
    struct common_type<_Tp>
    { typedef _Tp type; };

template<typename _Tp, typename _Up>
    struct common_type<_Tp, _Up>
    { typedef decltype(true ? declval<_Tp>() : declval<_Up>()) type; };

template<typename _Tp, typename _Up, typename... _Vp>
    struct common_type<_Tp, _Up, _Vp...>
    {
        typedef typename
        common_type<typename common_type<_Tp, _Up>::type, _Vp...>::type type;
    };

我理解第一,第二和第四个声明是如何工作的。然而,我不能设法理解第三个声明的工作原理。

I understand well how the first, second and fourth declarations work. However, I can't manage to understand how the third declaration works. Could someone try to explain the mechanism used here?

推荐答案

首先, std :: declval< T> ;()生成 T 类型的r值。尝试对该值执行任何操作都将失败,因此它只能在未评估的上下文中使用。接下来,三元运算符将其类型推断为两个参数共同的最专用类型(如果没有这样的类型,则它失败)。所以,表达式的类型

First off, std::declval<T>() yields an r-value of type T. Trying to do anything with the value will fail so it can only be used in an unevaluated context. Next, the ternary operator deduces its type as most specialized type common to both arguments (if there is no such type, it fails). So, the type of the expression

true? declval<T0>(): declval<T1>()

code> T0 和 T1 。所有剩余的是将这个表达式转换为一个类型,并确保它不被评估。 decltype(expr)就是这样。显然,逻辑的牛肉的两个参数版本:其他人在那里处理角的情况(一个参数),并利用两个参数版本产生常见类型的任意类型。

is the most specialized common type of T0 and T1. All what remains is to turn this expression into a type and making sure that it isn't evaluated. decltype(expr) does just this. Clearly, the two argument version of the beef of the logic: the others are there to deal with the corner case (one argument) and to leverage the two argument version to yield the common type of arbitrary types.

这篇关于std :: common_type实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆