c++ - 是否可以调用注入(inject)的 friend 模板函数?

标签 c++ c++11 friend function-templates

为了与类中的其他(非模板)函数保持一致,我想定义和调用友元模板函数。

我可以毫无问题地定义它(参见下面的函数 t)。

namespace ns{
struct S{
    void m() const{}
    friend void f(S const&){}
    template<class T>
    friend void t(S const&){}
};
template<class T>
void t2(S const& s){}
}

但是之后我无法以任何方式调用此 t 函数?

int main(){
    ns::S s;
    s.m();
    f(s);
//  t<int>(s); // error: ‘t’ was not declared in this scope (I was expecting this to work)
//  ns::t<int>(s); // error: ‘t’ is not a member of ‘ns’
//  ns::S::t<int>(s); // error: ‘t’ is not a member of ‘ns::S’
}

即使根本不可能,我也很惊讶我被允许定义它。

我用 gcc 8 和 clang 7 测试了这个。

最佳答案

你需要做的是一些前向声明。

下面两行代码应该在命名空间ns之前。

struct S; //Needed because S is used as a parameter in the function template
template<class T> void t(S const&);

然后这种形式的调用将在 main 中工作。

t<int>(s);

查看演示 here .

关于c++ - 是否可以调用注入(inject)的 friend 模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54158325/

相关文章:

c++ - std::async 与 std::launch::async 策略的行为

c++ - 使用基于范围的 For 循环和 Char 指针字符串

c# - 有 parent 和 child 的树结构

c++ - 友元运算符 << 无需重载

c++ - Linux 性能统计表现异常

c++ - 快速修复 C++ : Errors when compiling Acceptor

c++ - 函数必须只有一个参数

c++ - 缺少用于 map 初始化的构造函数

c++ - 模板类中的模板友元函数

c++ - 这是 gcc 优化错误吗?