C++ 重载/专门化最初使用模板右值引用声明的全局运算符
假设我们在库中定义了全局运算符(都在全局命名空间中)C++ 重载/专门化最初使用模板右值引用声明的全局运算符,c++,c++11,overloading,function-templates,forwarding-reference,C++,C++11,Overloading,Function Templates,Forwarding Reference,假设我们在库中定义了全局运算符(都在全局命名空间中) 模板 SpecialStream&运算符为什么运算符 template< class tAnyType > SpecialStream & operator << ( SpecialStream & os, tAnyType && value ) { return os.serialize( std::forward<tAnyType>( value ) ); }
模板
SpecialStream&运算符为什么运算符
template< class tAnyType >
SpecialStream & operator << ( SpecialStream & os, tAnyType && value )
{
return os.serialize( std::forward<tAnyType>( value ) );
}
SpecialStream & operator << ( SpecialStream & os, const MyClass & value )
{
return os << value.i << value.s.c_str();
}
#include <iostream>
using namespace std;
//---------------------------------------
// Radically simplified code from a library, in global namespace
class SpecialStream
{
public:
template< class tAnyType >
SpecialStream & serialize( tAnyType && value )
{
cout << value; // whatever, just an example <-- line 13
return *this;
}
};
// global operator that I’d like to overload/specialize for a specific class
template< class tAnyType >
SpecialStream & operator << ( SpecialStream & os, tAnyType && value )
{
return os.serialize( forward<tAnyType>( value ) ); // <-- line 22
}
//---------------------------------------
//---------------------------------------
// code from my project
class MyClass
{
public:
int i;
string s;
};
// Global operator overload/specialization (does not work! See question below)
// Tried const MyClass &, Myclass &&, MyClass
SpecialStream & operator << ( SpecialStream & os, const MyClass & value )
{
return os << value.i << value.s.c_str();
}
int main( int argc, char ** argv )
{
SpecialStream oss;
MyClass object;
oss << object; // compiler error! <-- line 46
}
1>test.cpp(13): error C2679: binary '<<': no operator found which takes a right-hand operand of type 'MyClass' (or there is no acceptable conversion)
note: could be 'std::basic_ostream<char,std::char_traits<char>> &std::basic_ostream<char,std::char_traits<char>>::operator <<(std::basic_streambuf<char,std::char_traits<char>> *)'
note: or 'std::basic_ostream<char,std::char_traits<char>> &std::basic_ostream<char,std::char_traits<char>>::operator <<(const void *)'
1> test.cpp(13): note: while trying to match the argument list '(std::ostream, MyClass)'
1> test.cpp(22): note: see reference to function template instantiation 'SpecialStream &SpecialStream::serialize<MyClass&>(tAnyType)' being compiled
1> with
1> [
1> tAnyType=MyClass &
1> ]
1> test.cpp(46): note: see reference to function template instantiation 'SpecialStream &operator <<<MyClass&>(SpecialStream &,tAnyType)' being compiled
1> with
1> [
1> tAnyType=MyClass &
1> ]