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

时间:2016-02-02 10:23:51

标签: c++ templates friend forward-declaration default-arguments

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

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

Visual Studio 2015似乎允许它。 gcc拒绝它。我在cppreference页面上找不到任何内容。

2 个答案:

答案 0 :(得分:2)

从C ++ 11开始,规则在14.1[temp.param]/9

中指定
  

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

直到C ++ 11,当然,14.1 / 9表示&#34;默认模板参数不应在朋友模板声明中指定。&#34;

(上面的内容几乎是逐字复制的,通过Default template parameters的cppreference,现在也在Template friends提到了

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

答案 1 :(得分:1)

如果您真的想使函数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;
}