使用" endl"模板功能的VS2015编译错误

时间:2016-07-03 20:18:32

标签: c++ templates visual-studio-2015 compiler-errors

#include "stdafx.h"
#include <iostream>

using namespace std;

// move operation is not implicitly generated for a class where the user has explicitly declared a destructor
class A {
public:
    friend inline void operator << (ostream &os, A& a) {
        os << "done" << endl;
    }
};

template <typename T>
void done(T a) {
    cout << a;
}

template<typename T>
void g(T h) {
    cout << h << endl;
}

int main()
{
    A a;
    done(a);
    // g(a); // with error: "mismatch in formal parameter list" and '<<': unable to resolve function overload.
    return 0;
}

作为评论,使用&#39; endl&#39;是如此奇怪,代码无法编译 错误:&#34;形式参数列表不匹配&#34;和&#39;&lt;&lt;&#39;:无法解决功能过载问题。

1 个答案:

答案 0 :(得分:2)

您应该返回对流的引用,以便链接函数调用

friend inline std::ostream& operator << (std::ostream &os, A& a) {
    os << "done" << endl;
    return os;
}

不是这个

friend inline void operator << (ostream &os, A& a) {
    os << "done" << endl;
}

使用时

friend inline void operator << (ostream &os, A& a) 

cout << h << endl;

是一个问题,因为operator<<void之间没有endl