gpt4 book ai didi

c++ - 没有 <> 的模板特化

转载 作者:IT老高 更新时间:2023-10-28 21:34:07 26 4
gpt4 key购买 nike

C++03和C++11在[temp.friend]第一段中有:

[编辑引用。第一次尝试错过了措辞的第二个差异。]

For a friend function declaration that is not a template declaration:

  1. if the name of the friend is a qualified or unqualified template-id, the friend declaration refers to a specialization of a function template, otherwise

  2. if the name of the friend is a qualified-id and a matching nontemplate function is found in the specified class or namespace, the friend declaration refers to that function, otherwise,

  3. [C++03:] if the name of the friend is a qualified-id and a matching specialization of a function template is found in the specified class or namespace, the friend declaration refers to that function template specialization, otherwise,

    [C++11:] if the name of the friend is a qualified-id and and a matching function template is found in the specified class or namespace, the friend declaration refers to the deduced specialization of that function template, otherwise,

  4. the name shall be an unqualified-id that declares (or redeclares) an ordinary (nontemplate) function.

[措辞的变化对我来说似乎是澄清。虽然我猜可能有不同的方式来解释 C++03 关于“在类或命名空间中找到专门化”的措辞。]

我对第三颗子弹很好奇。我编写此代码以尝试满足其要求,但 g++ 4.8.1 和 clang++ 3.4 都拒绝该代码,无论是使用 -std=c++03 还是 -std=c++11:

template <class T> class R;
namespace N {
template <class T> void test(const R<T>&);
}

template <class T>
class R {
friend void N::test(const R<T>&); // 8
int m;
};

template <class T>
void N::test(const R<T>& rec) { rec.m; }

int main() {
R<int> r;
N::test(r);
}

当然,如果我将第 8 行更改为

friend void N::test<>(const R<T>&);

第一个项目符号适用并且程序被接受。 g++ 打印一个有用的警告,说 friend “声明了一个非模板函数”,并建议我可能想要这样做。为了清晰和安全,代码可能也会获得更多样式点。

但是上面的代码不应该被第三个项目符号覆盖并且有效吗? friend 声明不是模板声明,它使用不是 template-idqualified-id 作为名称。并且没有与第二个项目符号匹配的非模板函数声明。

这只是两者共同的编译器错误吗?还是我误解了什么?如果有,有没有演示第三个项目符号的程序示例?

最佳答案

在//8 行,修改代码为: friend void N::test< R<T> >( R<T>&);
也正确。

friend void N::test<R<T>>(const R<T>&);//one type is friend with one type  #1
friend void N::test<>(const R<T>&);// one type is friend with one type #2

我使用一些代码证明 #1 等于 #2

最后,我试着回答你的问题。我不确定这是对的。

 friend void N::test(const R<T>&);

在实例化类 R 时,R<T>是已知类型。但是,功能是

声明为友元函数并且真的不实例化函数模板,那么

friend 功能是一个不存在的功能。从语法的角度来看,

编译器会提示你它是一个函数而不是一个模板

N::test (r);

在这个地方实例化了函数,但是编译器不匹配一个

friend 在R类中声明之前,因为你没有在R中声明为模板

类,你只需声明一个函数。

关于c++ - 没有 <> 的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19459283/

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