【问题标题】:Inheritance instead of typedef继承而不是 typedef
【发布时间】:2010-10-01 07:15:02
【问题描述】:

C++ 无法从 typedef 或 typedef 模板化类中生成模板。我知道如果我继承并将我的类设为模板,它将起作用。

例子:

// Illegal
template <class T>
typedef MyVectorType vector<T>;

//Valid, but advantageous?
template <class T>
class MyVectorType : public vector<T> { };

这样做是否有利,以便我可以“伪造” typedef 或者有更好的方法来做到这一点?

【问题讨论】:

  • 类似问题,相同答案:stackoverflow.com/questions/293988/…
  • 你的第二个例子也是无效的。您必须为 MyVectorType 编写自己的构造函数,因为您不能继承它们。

标签: c++ inheritance templates typedef


【解决方案1】:

C++0x 将使用 using 关键字添加模板类型定义。

您的解决方案声明了一种新类型,而不是类型“别名”,例如您不能用vector&lt;T&gt; 初始化MyVectorType &amp;(参考)。这对您来说可能不是问题,但如果是,但您不想在代码中引用向量,您可以这样做:

template <typename T>
class MyVectorType {
public:
  typedef std::vector<T> type;
};

【讨论】:

  • std::vector 有一个非虚拟析构函数,因此您需要小心不要通过 std::vector* 删除 MyVectorType*
  • 我并不是建议使用 MyVectorType 作为实际的数据类型,而是 MyVectorType::type,它是 std::vector 的 typedef,所以这里没有危险。跨度>
【解决方案2】:

继承不是你想要的。模拟模板化 typedef 的一种更惯用的方法是:

template <typename T> struct MyVectorType {
    typedef std::vector<T> t;
};

像这样引用 typedef:

MyVectorType<T>::t;

【讨论】:

    【解决方案3】:

    C++ 无法从 typedef 或 typedef 模板化类中生成模板。

    这取决于typedef 的含义:std::vector&lt;size_t&gt; 是合法的——尽管 size_t 是 typedef——而 std::stringtypedefstd::basic_string&lt;char&gt;

    【讨论】:

      【解决方案4】:

      你应该使用什么取决于它的行为方式(例如重载分辨率):

      • 如果你想让它成为一个新的独特类型

        class Foo : public Whatever {};
        

        但是,您现在可以将 Foo 的指针或引用传递给接受 Whatever 的函数,因此这变成了混合体。所以在这种情况下,使用private 继承和using Whatever::Foo 或自定义实现,来公开你想要的方法。

      • 如果你想要一个类型同义词

        using Foo = Whatever;
        

      前者的优点是可以预先声明一个类,但不能预先声明一个typedef。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-03
        • 2016-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-13
        • 1970-01-01
        相关资源
        最近更新 更多