2009-05-19 44 views
0

维基百科:Barton-Nackman技巧中使用的C++非模板成员是什么?

// 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,即可以实现编译时量纲分析(检查是否适用于一些变量的操作最终在可比的数字,喜欢的速度不相上下空间/时间,但没有加速度)。

任何人都可以解释我如何,或者至少解释我什么是非模板成员?

感谢

回答

4

自发明模式以来,语言的规则已经发生了变化,尽管我们注意不要打破它。换句话说,据我所知,它仍然有效,但原因不同于原来的原因。我认为我不会试图对这种模式进行尺寸分析,因为我认为今天有更好的方法。

我也认为这个例子太微不足道了。如前所述,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; 
}; 

免责声明:我不知道,如果这是它的应该使用的方式,但我有理由相信,它会像描述的那样工作。

+0

谢谢,这有助于我理解它。 – alvatar 2009-05-20 10:46:11

1

这些其实都是非模板非成员 - 在基本模板的比较运营商 - 他们得到派生类使用的ADL。模板成员会是这样的:


class C 
{ 
    ... 
    template < typename T > void DoGreatStuff(T t) { ... } 
    ... 
}; 
1

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