为什么下面的代码会产生编译错误?Google测试和运算符<< STL类型的过载
#include <iostream>
#include "gtest/gtest.h"
#include <utility>
namespace A {
//overloading operator << for std::pair
template<typename T1, typename T2>
std::ostream& operator<<(std::ostream& os, const std::pair<T1, T2>& p) {
return os << "pair:{" << p.first << ", " << p.second << "}";
}
struct C {
int x;
};
std::ostream& operator<<(std::ostream& os, const C& c) {
return os << c.x;
}
TEST(TestA, testA) {
std::pair<C, C> pair1;
std::pair<int, int> pair2;
EXPECT_EQ(0, 0) << pair1; //compiles
EXPECT_EQ(0, 0) << pair2; //doesn't compile
}
}
我使用Visual Studio 2015年错误的文字是:
错误C2679二进制“< <”:没有操作员发现这需要右手 数类型常量性病的” ::对'(或没有可接受 转换)... \ GTEST \ GTEST-message.h 131
如何变化的用户定义的类型到内置型有差别?
Upd。感谢@Kerrek SB,解释了错误。但是,现在还有另一个问题:我应该如何超载运算符< <的std::pair
才能够像我的代码一样使用它?
因为名称空间查找不在命名空间'A'中查找您的运算符过载。 –
但是它发现它对'对'。为什么它只是没有找到'对'? –
因为模板和ADL。 'C'在命名空间'A'中,所以'A'是查找关联的命名空间。 –