【问题标题】:C++ type alias with using keyword带有 using 关键字的 C++ 类型别名
【发布时间】:2019-10-12 00:29:38
【问题描述】:

是否可以在 c++ 中使用 using 关键字定义此类类型别名? 语法如何?我试过using const_type = typename const T::type 不行。

template <typename T>
    class DoubleBuffer {
    typedef T value_type;
    typedef T& reference;
    typedef T const & const_reference;
    typedef T* pointer;

    const_reference operator[](const size_t pos){
        ...
    }
};

【问题讨论】:

  • using const_type = const typename T::type;
  • using const_type = const T;
  • 你的问题不是很清楚。您是否尝试将示例中的所有 typedefs 替换为 using 关键字?
  • @InnocentBystander 是的,但我真的很困惑何时使用 typename 何时不使用。这似乎是我的代码的问题。
  • @evanxg852000 请参阅Dependent names 下的类型名称消歧器部分。

标签: c++ c++17 typedef type-alias


【解决方案1】:
template <typename T>
class DoubleBuffer {
public:
    using value_type = T;
    using reference = T&;
    using const_reference = T const &;
    using const_type = const typename T::type;
    using pointer = T*;
    //...
};

Live Demo

或者:

template <typename T>
class DoubleBuffer {
public:
    using value_type = T;
    using reference = T&;
    using const_reference = T const &;
    using const_type = const T;
    using pointer = T*;
    //...
};

Live Demo

取决于 T 的实际含义 - 定义了嵌套 typestruct/class 或独立类型。

【讨论】:

  • 请提供任何说明为什么在某些情况下使用typename using const_type = const typename T::type; 的文档?
  • 当引用其父类型依赖于模板的嵌套类型时,您必须使用typename
猜你喜欢
  • 1970-01-01
  • 2010-10-07
  • 1970-01-01
  • 2011-10-01
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多