【问题标题】:Is this using alias for a function type (not pointer) the same as this typedef这是否使用与此 typedef 相同的函数类型(不是指针)的别名
【发布时间】:2016-01-15 12:43:26
【问题描述】:

这些是一样的吗?

using on_receipt = void (const string);

typedef void on_receipt(const string);

这些不是函数指针的别名,而是实际的函数类型。他们都编译得很好。奇怪的是,typedef 版本至少有函数名称的占位符,但由于 using 将此占位符移动到 = 之前,因此返回和参数之间没有任何区别,看起来像它可能不正确或具有误导性。

【问题讨论】:

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


    【解决方案1】:

    是的,他们是:

    [dcl.typedef]

    2 typedef-name 也可以由 别名声明。 using 关键字后面的标识符变为 一个 typedef-name 和可选的属性说明符序列 标识符属于该类型定义名称。它具有相同的语义 好像它是由 typedef 说明符引入的。特别是,它 没有定义新类型。

    Live Example

    #include <string>
    #include <type_traits>
    
    int main()
    {
        using on_receipt1 = void (const std::string);    
        typedef void on_receipt2(const std::string);
        static_assert(std::is_same<on_receipt1, on_receipt2>::value, "");
    }
    

    【讨论】:

    • 可能是确凿证据的最佳想法 =)。荣誉。 +1
    • 一个不需要&lt;type_traits&gt; 的更简单的测试是using on_receipt = void (const std::string); typedef void on_receipt(const std::string);。您可以重新声明 typedef - 但前提是两个声明都命名相同的类型。
    【解决方案2】:

    你想错了。 on_receipt 不是“函数名称的占位符”,它是您介绍的类型名称。想想用法。

    您会像on_receipt function_variable; 一样使用它,因此您的解释实际上是一种误导,因为您引用函数的“名称”不是on_receipt,而是function_variable

    我会说函数的typedef 语法相当奇怪。在using 样式中,一侧有类型名称,另一侧有定义它的东西。在 typedef 样式中,您可以将其交错。

    typedef 有点像函数声明,但实际上不是;这是一个类型声明。我觉得那很乱。

    哦,当然,这些语句是等价的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 2013-09-09
      • 2011-03-28
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多