c++templatesfriendforward-declarationdefault-arguments

friend function template with default template argument


Is it allowed to provide a default to a template argument in a friend declaration?

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

Visual Studio 2015 seems to allow it. gcc refuses it. I couldn't find anything on it on the cppreference page.


Solution

  • As of C++11, the rule is, specified in 14.1[temp.param]/9

    If a friend function template declaration specifies a default template-argument, that declaration shall be a definition and shall be the only declaration of the function template in the translation unit.

    Until C++11, of course, 14.1/9 said "A default template-argument shall not be specified in a friend template declaration."

    (the above is copied pretty much verbatim, by cppreference at Default template parameters, now also mentioned at Template friends)

    So, to make your program valid C++, define your friend template inside the class, don't just declare.