【问题标题】:What's the difference between using-style and typedef-style? [duplicate]using-style 和 typedef-style 有什么区别? [复制]
【发布时间】:2013-09-18 21:36:15
【问题描述】:
using IntegerType1 = int;
typedef int IntegerType2;

int main()
{
    IntegerType1 n1 = 1; // OK
    IntegerType2 n2 = 2; // OK
}

我的问题是:

  1. using-style和typedef-style有什么区别?

  2. 既然我们已经有了 typedef-style,那么让 using-style 成为 C++ 标准的动机是什么?

【问题讨论】:

  • 已经有多个问题了。

标签: c++ c++11 types typedef using


【解决方案1】:

引入了“使用样式”以允许模板化类型定义:

template< typename T >
using int_map = std::map< int, T >;

typedef 无法做到这一点。我自己觉得很奇怪,决定使用using 而不是typedef 作为关键字,但我猜委员会一定发现了扩展typedef 语法的问题。

【讨论】:

  • 对于using,新定义的类型的名称总是在表达式的左边。使用typedef,名称可以位于表达式的中间。所以using 提高了可读性,恕我直言。
  • @VasilyBiryukov 确实,我个人更喜欢新的using-syntax,比旧的typedef-syntax 好得多。当您需要与alignas 应用对齐时,它还有其他好处。
【解决方案2】:

我发现即使对于非模板,可读性也大大提高:

typedef void (*FunctionPtr)();  // right-to-left, identifier in the middle of the definition
using FunctionPtr = void (*)(); // left-to-right, same as variables

这可能是次要的,但在模板元编程中,这种语法优势使程序更易于阅读,并使模板元函数更容易重构为constexpr 函数。本质上替换

using T = type_expression;
constexpr auto v = value_expression;

此外(呼吁权威),它也在draft Effective C++11/14 guidelines中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-01
    • 2016-01-02
    • 2015-01-11
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2016-11-25
    • 2016-06-14
    相关资源
    最近更新 更多