声明模板函数 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/