【问题标题】:Parameterized typedef possible?参数化 typedef 可能吗?
【发布时间】:2013-04-30 18:38:09
【问题描述】:

我想知道是否有可能有某种参数化的 typedef。

为了说明,在我的代码中我使用了这个 typedef:

typedef std::queue<std::vector<unsigned char>, std::deque<std::vector<unsigned char> > > UnsignedCharQueue;

正如你所看到的,这是一个相当笨拙的结构,所以 typedef 是有意义的。但是,如果我想拥有其他数据类型的队列,我需要事先明确定义它们。

所以我在想是否可以使用这样的构造:

typedef std::queue<std::vector<T>, std::deque<std::vector<T> > > Queue<T>;

private:
    Queue<unsigned char> mMyQueue;

类似于 Java 中的泛型。

【问题讨论】:

标签: c++ templates generics


【解决方案1】:

在C++11中,可以使用模板别名,如:

template<typename T>
using my_alias = some_class_template<T>;

// ...
my_alias<T> obj; // Same as "some_class_template<T> obj;"

所以你的情况是:

template<typename T>
using Queue = std::queue<std::vector<T>, std::deque<std::vector<T> > >;

还要注意,在 C++11 中,你不需要在右尖括号之间留一个空格,所以上面可以改写如下:

template<typename T>
using Queue = std::queue<std::vector<T>, std::deque<std::vector<T>>>;
//                                                               ^^^

在 C++03 中,您可以这样定义 Queue 元函数:

template<typename T>
struct Queue
{
    typedef std::queue<std::vector<T>, std::deque<std::vector<T> > > type;
};

然后你会以这种方式使用它:

Queue<int>::type obj;

如果您在带有参数T(如下所示)的模板中使用它,请不要忘记typename 消歧器:

template<typename T>
struct X
{
    typename Queue<T>::type obj;
//  ^^^^^^^^
}

【讨论】:

  • 该死的,你的速度快如闪电。我打算发布这个。
  • @H2CO3:我很幸运能够尽快收到新问题通知;)
  • @VaughnCato:在问题页面中...“1 个新活动的问题”
  • 为没有 C++11 的人展示一种元函数方法可能会很好using
  • 谢谢!附加信息帮助很大! C03 语法并不完美,但仍然比使用 typedef 更好。 :)
【解决方案2】:

是的,它是这样工作的:

template <typename T> using Queue = std::queue<std::vector<T>, std::deque<std::vector<T> > >;

【讨论】:

  • g++ c
  • @Devolus:使用 g++,确保将 -std=c++11 指定为命令行参数之一。
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 2013-02-23
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多