gpt4 book ai didi

c++ - 选择声明模板友元的语法背后的基本原理是什么?

转载 作者:可可西里 更新时间:2023-11-01 16:38:26 25 4
gpt4 key购买 nike

声明模板函数 friends 涉及一些非常不直观的语法,即使对于 C++ 也是如此!选择额外 <> 的语法背后的基本原理是什么?需要吗?使用 template 不是更有意义吗?关键字?

对于那些不知道这一点的人,这里有一个你可能会尝试做的例子:

template <typename T>
class Foo
{
int x;
friend void bar(Foo<T>);
};

template <typename T>
void bar(Foo<T> f)
{
std::cout << f.x;
}

如果您尝试调用 bar(Foo<T>()) ,您将收到链接器错误。

要解决这个问题,你必须转发声明bar (因此也是 Foo )然后粘贴一个奇怪的位置 <>在好友声明中。

template <typename T> class Foo;
template <typename T> void bar(Foo<T>);

template <typename T>
class Foo
{
int x;
friend void bar<>(Foo<T>); // note the <> (!?)
};

template <typename T>
void bar(Foo<T> f)
{
std::cout << f.x;
}

我的问题是,<> 背后的基本原理是什么?句法?使用 template 不是更直观吗?关键字或类似的东西?

编辑:为了澄清,我已经知道 为什么 <> 是必需的,我想知道的是为什么他们选择使用 <> 来消除歧义而不是其他一些更直观的语法。

最佳答案

等等。您没有声明好友模板。您将模板的特化声明为 friend !因此,你为什么要放一个 template那里的条款?

命名函数模板特化的语法是 teplateName<ArgumentList> ,这就是您在 friend 声明中根据标准使用的内容。

如果你想友好整个模板和所有生成的特化和显式特化,你仍然可以这样做,然后你可以使用模板子句

template<typename U>
friend void bar(Foo<U>);

关于c++ - 选择声明模板友元的语法背后的基本原理是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6803099/

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