代码之家  ›  专栏  ›  技术社区  ›  alvatar

Barton Nackman技巧中使用的C++非模板成员是什么?

  •  0
  • alvatar  · 技术社区  · 16 年前

    维基百科:

    // A class template to express an equality comparison interface.
    template<typename T> class equal_comparable
    {
        friend bool operator==(T const &a, T const &b) { return  a.equal_to(b); }
        friend bool operator!=(T const &a, T const &b) { return !a.equal_to(b); }
    };
    
    class value_type
    // Class value_type wants to have == and !=, so it derives from
    // equal_comparable with itself as argument (which is the CRTP).
         : private equal_comparable<value_type>
    {
    public:
        bool equal_to(value_type const& rhs) const; // to be defined
    };
    

    这应该是 Barton-Nackman 这可以实现编译时维度分析(检查应用于变量的某些操作是否以可比的数字结束,比如速度与空间/时间相当,但没有加速度)。

    有人能解释我如何,或者至少解释我什么是非模板成员吗?

    谢谢

    3 回复  |  直到 16 年前
        1
  •  4
  •   j2.    16 年前

    自从模式被发明以来,语言的规则已经改变了,尽管人们注意不要破坏它。换句话说,据我所知,它仍然有效,但原因与最初不同。我不认为我会尝试在这个模式上进行维度分析,因为我认为今天有更好的方法可以做到这一点。

    我还认为这个例子太过琐碎,没有帮助。如前所述 equal_comparable<value_type> 原因 operator== operator!= 对于 value_type 出现。因为它们是非成员,所以继承是私有的并不重要,在解析调用时,它们仍然是可供选择的。在这个例子中很难看出这一点。但是,假设您将模板参数添加到 equal_comparable 还有其他一些事情:

    template<typename U, typename V> class equal_comparable
    {
        friend bool operator==(U const &a, V const &b) { return  a.equal_to(b); }
        friend bool operator!=(U const &a, V const &b) { return !a.equal_to(b); }
    };
    
    class some_other_type 
    {
        bool equal_to(value_type const& rhs) const;
    };
    
    class value_type
    : private equal_comparable<value_type>,      // value_type comparable to itself
      private equal_comparable<some_other_type>  // value_type comparable to some_other_type
    {
    public:
        bool equal_to(value_type const& rhs) const;
        bool equal_to(some_other_type const& rhs) const;
    };
    

    免责声明:我不知道是不是这样 想象上的 可以使用,但我有理由相信它会像描述的那样工作。

        2
  •  1
  •   Nikolai Fetissov    16 年前

    这些实际上是非模板非成员(基本模板中的比较运算符),ADL将它们用于派生类。模板成员如下:

    
    class C
    {
        ...
        template < typename T > void DoGreatStuff( T t ) { ... }
        ...
    };
    
        3
  •  1
  •   Bojan Resnik    16 年前

    实例化 equal_comparable<value_type> 在里面 value_type 类使编译器生成两个比较函数:

    friend bool operator==(value_type const &a, value_type const &b) { return  a.equal_to(b); }
    friend bool operator!=(value_type const &a, value_type const &b) { return !a.equal_to(b); }
    

    这些函数是非模板函数,因为它们不依赖于任何模板参数,但它们也是非成员,因为它们声明为 friend .