【问题标题】:Can "typedef typename" be replaced by "using" keyword in C++ 11在 C++ 11 中,“typedef typename”可以替换为“using”关键字吗
【发布时间】:2017-08-07 14:12:41
【问题描述】:

我知道“using”关键字可以用作模板别名和类型别名,但我没有看到有人提到“typedef typename”可以替换为“using”。可以吗?

【问题讨论】:

    标签: c++11 typedef using typename


    【解决方案1】:

    以下形式的声明

    typedef typename something<T>::type alias;
    

    可以替换为

    using alias = typename something<T>::type;
    

    typename 仍然是必需的,但它确实看起来更整洁,并且将 = 放在行的中间是美观的,因为我们正在定义一个别名。使用的主要卖点是可以模板化。

    template <typename T>
    using alias = typename something<T>::type;
    

    你不能单独使用 typedef 来做到这一点。 C++98 的等价物就是这种略显怪异的语法。

    template <typename T>
    struct Alias {
      typedef typename something<T>::type type;
    };
    
    // Then refer to it using typename Alias<T>::type.
    // Compare to the C++11 alias<T>, which is much simpler.
    

    using 相对于typedef 的另一个主要卖点是在定义函数别名时看起来更简洁。比较

    // C++98 syntax
    typedef int(*alias_name)(int, int);
    // C++11 syntax
    using alias_name = int(*)(int, int);
    

    【讨论】:

    • "使用别名 = typename something::type;"你能解释一下为什么仍然需要“=”右侧的“typename”吗?
    • @PeterHan typename 从来没有必要,除非代码不明确,唯一的其他用途是它可以替换模板中的class
    【解决方案2】:

    using 可以替换类型声明,以防您将其用作另一种类型的别名或可以声明此类型。语法是:

    使用标识符 attr(optional) = type-id ; (1)

    模板 使用标识符 attr(可选) = type-id ; (2)

    type-id - 抽象声明符或任何其他有效的 type-id(可能引入新类型,如 type-id 中所述)。 type-id 不能直接或间接引用标识符。

    所以,这不能用单个using代替,你需要两个:

    typedef struct MyS 
    {
       MyS *p;
    } MyStruct, *PMyStruct;
    

    【讨论】:

      猜你喜欢
      • 2011-05-24
      • 1970-01-01
      • 2015-07-24
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      相关资源
      最近更新 更多