我有许多向量类,我想为其实现一个通用流运算符,如下所示:
template <typename T>
std::ostream& operator<<(std::ostream& os, const T& v)
{
for (int i = 0; i < T::num_elems; ++i)
{
os << " " << v.a[i];
}
return os;
}
这几乎可以工作,除了我os << " " << ...
当然会得到一个错误,因为它是模棱两可的。我怎样才能消除歧义并强制<<
操作员std::
在这里使用?
或者,如何将这个模板化流运算符的使用限制为我的向量类?我已将向量类和流运算符放入单独的命名空间中,但这似乎还不够。
实际错误消息的开始:
foo.cpp:73: error: ambiguous overload for 'operator<<' in 'os << " "'
/usr/include/c++/4.2.1/ostream:169:0 /usr/include/c++/4.2.1/ostream:169: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char, _Traits = std::char_traits<char>] <near match>
/usr/include/c++/4.2.1/ostream:177:0 /usr/include/c++/4.2.1/ostream:177: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>] <near match>
/usr/include/c++/4.2.1/ostream:185:0 /usr/include/c++/4.2.1/ostream:185: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(bool) [with _CharT = char, _Traits = std::char_traits<char>]
...
进一步澄清:流运算符仅用于测试工具(UnitTest ++),它不是公共 API 的一部分。向量类也是小的自定义固定大小向量(实际上只是简单的数组),而不是 C++ 向量。
我需要使用它的向量类之一的精简示例:
struct VectorClass {
enum { num_elems = 16 };
int32_t a[num_elems];
};