gpt4 book ai didi

c++ - 顺序对类模板中函数的特化有影响吗

转载 作者:太空狗 更新时间:2023-10-29 21:08:14 25 4
gpt4 key购买 nike

考虑类似...

template<typename T>
class Vector {
...
bool operator==( const Vector<float> &rhs ) {
// compare and return
}

bool operator==( const Vector<T> &rhs ) {
// compare and return
}
...
};

请注意特化是如何高于非特化版本的。如果我将专用版本放在非专用版本的下方Vector<float> 会是吗? == 比较仍然按预期工作吗?出于某种原因,我想我记得读过,如果您将特化放在这种情况下,那么当编译器查看 header 时,它会首先看到默认值,看到它有效,然后使用它。

最佳答案

您的示例代码不是专门化的,而是重载的。顺序确实很重要(尽管在您的代码中不重要),因为函数需要在 C++ 中已知之前声明。因此,如果一个重载调用另一个重载,或者如果中间的另一个函数调用重载集,则调用可能会在不需要的地方结束。您的示例代码有效且通用。

For some reason I think I remember reading that if you put the specialization below in this scenario then when the compiler looks through the header, it will see the default first, see that it works, and use that.

你在想下面的规则

If a template, a member template or the member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.

我忍不住要引用标准中关于特化的搞笑说法

The placement of explicit specialization declarations for function templates, class templates, member functions of class templates, static data members of class templates, member classes of class templates, member class templates of class templates, member function templates of class templates, member functions of member templates of class templates, member functions of member templates of non-template classes, member function templates of member classes of class templates, etc., and the placement of partial specialization declarations of class templates, member class templates of non-template classes, member class templates of class templates, etc., can affect whether a program is well-formed according to the relative positioning of the explicit specialization declarations and their points of instantiation in the translation unit as specified above and below. When writing a specialization, be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation.

关于c++ - 顺序对类模板中函数的特化有影响吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3535287/

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