c++ - 非成员模板友元函数默认参数值错误

标签 c++ templates default-parameters friend-function non-member-functions

为什么下面的代码可以用 GCC 编译,但不能用 Clang 编译?谁是对的,为什么?

class TF
{
        private:
                struct S
                {
                };

        template <typename T> friend void F(T x, S s, int v = 5);
};

template <typename T>
void F(T x, TF::S s, int v)
{
}

我在使用 clang++ 时遇到以下错误:

    error: friend declaration specifying a default argument must be a definition
        template <typename T> friend void F(T x, S s, int v = 5);
                                          ^
    error: friend declaration specifying a default argument must be the only declaration
    void F(T x, TF::S s, int v)
         ^
    note: previous declaration is here
        template <typename T> friend void F(T x, S s, int v = 5);

GCC版本:g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0

Clang版本:clang版本6.0.0-1ubuntu2

如何解决这个问题?

最佳答案

How do I resolve this?

正如错误消息所示,您必须定义函数模板才能具有默认参数:

    template <typename T>
    friend void F(T x, S s, int v = 5) {
        // ...
    }

如果您不希望这样,您可以删除默认参数并添加充当代理的重载:

    template <typename T>
    friend void F(T x, S s, int v);

// ...

template <typename T>
void F(T x, TF::S s, int v) {
    // ...
}

template <typename T>
void F(T x, TF::S s) { F(x, s, 5); }

另一种选择是对函数进行前向声明:

template <typename T, typename S>
void F(T x, S s, int v = 5);

class TF {
private:
    struct S {};

    template <typename T, typename S>
    friend void F(T x, S s, int v);
};

template <typename T, typename S>
void F(T x, S s, int v) {
    static_assert(std::is_same_v<S, TF::S>);
    // ...
}

关于c++ - 非成员模板友元函数默认参数值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63296924/

相关文章:

c++ - 更改 while 循环以适应两种情况

python - 如何在函数内部(以非阻塞方式)使用 zmq 在客户端请求时获取函数的状态?

c++ - 编译时通过索引访问类模板的成员

elixir - 通过添加可选参数 elixir 实现函数 def 冲突

c++ - 模板函数作为默认模板参数

c++ - 如何在 QT 应用程序中的嵌入式 Python 中休眠

c++ - 没有合适的默认构造函数可用 - 默认构造函数在哪里调用?

c++ - std::make_unsigned 没有给出预期的结果

c++ - 按函数名参数化模板 c++11

python - 具有默认参数的函数出现问题