选择用来声明模板好友的语法背后的原理是什么? [英] What is the rationale behind the syntax chosen to declare template friends?
问题描述
即使对于C ++,声明模板函数的朋友也涉及到一些难以理解的语法!选择所需的额外<>
语法的背后原理是什么?使用template
关键字更有意义吗?
Declaring template function friends involves some incredibly unintuitive syntax, even for C++! What is the rationale behind the choice of syntax for the extra <>
needed? Wouldn't it make more sense to use the template
keyword?
对于那些对此一无所知的人,这是您可以尝试做的事的一个示例:
For those that don't know about this, here is an example of what you might try to do:
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>())
,则会出现链接器错误.
If you try to call bar(Foo<T>())
, you will get linker errors.
要解决此问题,您必须转发声明bar
(因此是Foo
),然后在好友声明中插入一个奇怪的<>
.
To solve this, you have to forward declare bar
(and therefore Foo
) and then stick an oddly placed <>
in the friend declaration.
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
关键字或类似的文字会更直观吗?
My question is, what is the rationale behind the <>
syntax? Wouldn't it be more intuitive to use the template
keyword or something along those lines?
为明确起见,我已经知道为什么的必需,我想知道的是为什么他们选择使用<>消除歧义,而不是其他一些歧义.更直观的语法.
To clarify, I already know why the <> is required, what I want to know is why they chose to use <> to disambiguate it instead of some other more intuitive syntax.
推荐答案
等待.您尚未声明朋友模板.您将模板的专业化声明为朋友!因此,为什么要在其中放置template
子句?
Wait. You are not declare a friend template. You declare a specialization of a template as friend! As such, why would you want to put a template
clause there?
函数模板的专业名称的语法是通过teplateName<ArgumentList>
命名的,这就是您根据朋友声明中的标准"使用的语法.
The syntax to name specializations of function templates is by teplateName<ArgumentList>
, and that is what you shall use according to the Standard in the friend declarations.
如果您想与整个模板以及生成的所有专业化知识和明确的专业化知识保持友好,您仍然可以这样做,然后可以使用模板子句
If you want to befriend the whole template and all specializations generated and explicitly specialized, you can still do that, and then you can use a template clause
template<typename U>
friend void bar(Foo<U>);
这篇关于选择用来声明模板好友的语法背后的原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!