具有默认模板参数的友元函数模板

friend function template with default template argument

本文关键字:友元 函数模板 参数 默认      更新时间:2023-10-16

是否允许在友元声明中提供模板参数的默认值?

class A {
    int value;
public:
    template<class T = int> friend void foo();
};

Visual Studio 2015似乎允许这样做。 海湾合作委员会拒绝了。 我在cpp首选项页面上找不到任何内容。

自 C++11 起,该规则在 14.1[temp.param]/9 中指定

如果友元函数模板声明指定了默认模板参数,则该声明应是一个定义,并且应该是翻译单元中函数模板的唯一声明。

当然,直到 C++11 之前,14.1/9 说"默认模板参数不得在友元模板声明中指定。

(以上内容几乎是逐字复制的,由默认模板参数中的cpp首选项复制,现在在模板朋友中也提到)

因此,为了使您的程序C++有效,请在类中定义您的朋友模板,不要只是声明。

如果你真的想保持你的函数 foo() 全局,你可以试试这个:

class A
{
    int value;
public:
    template<class T> friend void foo();
};
template<class T = int> void foo()
{
    //you can use private member of A
    A foo;
    auto value = foo.value;
}