gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:54:59 26 4
gpt4 key购买 nike

来自维基百科:

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

谁能给我解释一下,或者至少解释一下非模板成员是什么?

谢谢

最佳答案

自模式发明以来,语言规则发生了变化,但注意不要破坏它。换句话说,据我所知,它仍然有效,但出于与最初不同的原因。我不认为我会尝试基于这种模式进行维度分析,因为我认为今天有更好的方法可以做到这一点。

我也认为这个例子太简单了,没有什么帮助。如前所述,equal_comparable<value_type> 的实例化原因operator==operator!=对于 value_type出现。由于他们不是成员,因此继承是私有(private)的并不重要,在解决调用时他们仍然有资格被选择。在这个例子中很难看出重点。但是,假设您将模板参数添加到 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;
};

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

关于c++ - Barton-Nackman 技巧中使用的 C++ 非模板成员是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/883109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com