类模板的朋友功能的显式专门化 [英] Explicit specialization of friend function for a class template

查看:74
本文介绍了类模板的朋友功能的显式专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在此处阅读litb对问题的回答,其中他详细介绍了如何创建专业朋友功​​能一个模板模板

I was reading litb's answer to a question here, where he details how to create a specialized friend function of a class template.

我试图创建一个示例,该示例完全符合他的建议(最后是 code ):

I tried to create an exemplar which did just what he suggests (code at the end):

// use '<>' to specialize the function template with the class template's type
friend std::ostream& operator<< <>(std::ostream& os, const foo<T>& f)

这会导致出现编译器错误

error: defining explicit specialization ‘operator<< <>’ in friend declaration

中明确声明专业化中的template参数也不起作用:

Explicitly declaring the template parameter in the specialization doesn't work either:

friend std::ostream& operator<< <T>(std::ostream& os, const foo<T>& f) // same error

另一方面,从使用专业化改为使用朋友功能模板代替了的工作:

On the other hand, changing from using a specialization to use a friend function template instead does work:

template<typename U>
friend std::ostream& operator<<(std::ostream& os, const foo<U>& f) // this works

所以我的问题是:


  • 是什么引起了第一个错误?

  • 如何我可以明确地专门化 ostream运算符来进行周围的类模板专业化吗?

  • what is causing the first error?
  • how can I explicitly specialize the ostream operator for the surrounding class template specialization?

下面的示例代码:

#include <iostream>

// fwd declarations
template<typename T> struct foo;
template<typename T> std::ostream& operator<<(std::ostream&, const foo<T>&);

template<typename T>
struct foo
{
    foo(T val)
        : _val(val)
    {}

    friend std::ostream& operator<< <>(std::ostream& os, const foo<T>& f) // error line
    //template<typename U>
    //friend std::ostream& operator<<(std::ostream& os, const foo<U>& f) // this works
    {
        return os << "val=" << f._val;
    }

    T _val;
};


int main()
{
    foo<std::string> f("hello world");
    std::cout << f << std::endl;
    exit(0);
}


推荐答案

在litb的示例中,他只是在课堂上宣布专业为朋友。他没有定义专业化,这就是您的代码正在做的事情。您不允许在类声明(或任何非命名空间范围)中定义特殊化。

In litb's example, he's just declaring the specialization as a friend in the class. He's not defining the specialization, which is what your code's doing. You're not allowed to define a specialization in a class declaration (or any non-namespace scope).

您需要的是这样的东西:

What you need is something like:

template <class T>
class foo;

template<class T>
std::ostream& operator<<(std::ostream& os, const foo<T>& f)
{
    return os << "val=" << f._val;
}

template<typename T> 
struct foo
{
    // ...
private:
    friend std::ostream& operator<< <>(std::ostream& os, const foo<T>& f);
    T _val;
};

这篇关于类模板的朋友功能的显式专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆