问题重载<<运算符在模板类中

时间:2019-03-16 16:04:00

标签: c++ templates

在类之外重载<<可以工作:

template <typename T>
class A
{
public:
    T x;
};

template <typename T>
std::ostream & operator<<(std::ostream & ostream, const A<T> & a);

template<typename T>
std::ostream & operator<<(std::ostream & ostream, const A<T>& a)
{
    return ostream << a.x;
}

在类内部重载<<:

template <typename T>
class A
{
public:
    T x;
    friend std::ostream & operator<<(std::ostream & ostream, const A & a)
    {
        return ostream << a.x;
    }
};

但这不起作用!

template <typename T>
class A
{
public:
    T x;
    friend std::ostream & operator<<(std::ostream & ostream, const A & a);
};

template <typename T>
std::ostream & operator<<(std::ostream & ostream, const A<T> & a)
{
    return ostream << a.x;
}

有人可以解释我为什么吗? 我正在使用Microsoft的可视c ++编译器。

这是我得到的错误:

Error LNK2019 unresolved external symbol 
"class std::basic_ostream<char,struct std::char_traits<char> > &
   __cdecl operator<<(class std::basic_ostream<char, 
     struct std::char_traits<char> > &,class A<float> const &)"
(??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$A@M@@@Z)
 referenced in function _main ...

编辑: 根据要求,这是完整的代码,我没有使用g ++对其进行测试,仅在Visual Studio中进行了测试。

#include <iostream>

template <typename T>
class A
{
public:
    T x;
    friend std::ostream & operator<<(std::ostream & ostream, const A & a);
};

typedef A<float> Af;

int main()
{
    std::cout << Af{ 2.4 } << "\n";
}

template <typename T>
std::ostream & operator<<(std::ostream & ostream, const A<T> & a)
{
    return ostream << a.x;
}

0 个答案:

没有答案