I have some problems overloading operators with template members and using make_pair:
class MyArchive
{
public:
template <class C> MyArchive & operator<< (C & c)
{
return (*this);
}
};
class A
{
};
int main()
{
MyArchive oa;
A a;
oa << a; //it works
oa << std::make_pair(std::string("lalala"),a); //it doesn't work
return 0;
}
I get this interesting error:
/home/carles/tmp/provaserialization/main.cpp: In function ‘int main()’:
/home/carles/tmp/provaserialization/main.cpp:30: error: no match for ‘operator<<’ in ‘oa << std::make_pair(_T1, _T2) [with _T1 = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _T2 = A]((a, A()))’
/home/carles/tmp/provaserialization/main.cpp:11: note: candidates are: MyArchive& MyArchive::operator<<(C&) [with C = std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, A>]
Any ideas about why it doesn’t find operator<< in the second case?
The parameter of
operator<<should beconst:Because
std::make_pairreturns a temporary object which cannot be bound to non-const parameter. But a temporary object can be bound to aconstparameter, since then the life of the temporary extends, till the end of the called function.A simple demonstration:
Output:
See the output yourself here: http://www.ideone.com/16DpT
EDIT:
Of course, the above output explains only that temporary is bound to the function with const-parameter. It doesn’t demonstrate life-extension. The following code demonstrates life-extension:
Output:
The fact that
A is destructedafter the function printsconst parameterdemonstrates that A’s life is extended till the end of the called function!Code at ideone : http://www.ideone.com/2ixA6