struct :: type +使用和仅使用?

时间:2017-09-21 11:51:21

标签: c++ c++14

我在相似性上看到了很多代码:

namespace _private {
    template <class T>
    struct identity
    {
        using type = T;
    };
}
template <class T>
using identity = typename _private::identity<T>::type;

简单之处有什么区别:

template<class T>
using identity = T;

其他样本:

template <typename A>
struct Int4 : std::integral_constant<int, 4> {};

VS

template <typename A>
using Int4 = std::integral_constant<int, 4>;

2 个答案:

答案 0 :(得分:4)

::type标识块模板类型扣除。原始使用没有。

struct Int4是与积分常数4不同的类型;它只是将常量作为公共父类型。使用不是一种独特的类型。

这两种差异都可能产生广泛的连锁效应,这些效应过于广泛,无法在SO答案中涵盖。

答案 1 :(得分:1)

这个问题的答案实际上是“阅读C ++教科书”,但是,我觉得在使用C ++库时,有一个更加细微的答案是有用的。

typedefusing不会声明新类型,而只是现有类型的别名。如果您使用大型库并且希望转发声明定义但定义本身是类型定义的,这可能会导致非常微妙但令人讨厌的错误。

大包括

struct my_s {};
using my_struct = my_s;
// ...

<强>来源

//#include "large_include.h"
struct my_struct;
#include "large_include.h"    // compiler error, no issue if we do `struct my_s;`

即使您可能会在当前的C ++理解水平上看到这些名称与非常相似的实体,但编译器对它们的处理方式也大不相同。别名和新类型都很棒:了解它们之间的区别。

此外,添加新类型显然是不同的。

#include <iostream>
#include <type_traits>
struct a {};
struct b: a {};
struct c: a {};
using d = c;

int main()
{
     std::cout << std::is_same<b, c>::value << std::endl; // false
     std::cout << std::is_same<c, d>::value << std::endl; // true
}
相关问题