2011-02-16 54 views
2

我有一些问题超载模板成员运营商和使用make_pair:模板运营商<<重载和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; 
} 

我得到这个有趣错误:

/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>] 

为什么它的任何想法在第二种情况下没有找到operator<<

回答

4

operator<<的参数应该是const

template <class C> MyArchive & operator<< (const C & c) 

std::make_pair由于返回不能被结合到非const参数临时对象。但临时对象可以绑定到const参数,因为此时临时对象的生命期会延长,直到被调用函数结束。


一个简单的演示:

template<typename T> 
void f(T & c) { cout << " non-const parameter" << endl; } 

template<typename T> 
void f(const T & a) { cout << "const parameter" << endl; } 

int main() 
{ 
    f(make_pair(10,20.0)); //this calls second function! 
} 

输出:

const parameter

看到输出自己的位置:http://www.ideone.com/16DpT

编辑:

当然,上述OUTP ut只解释了临时参数与const参数绑定在一起的功能。它没有展现生命延长。下面的代码演示寿命延长:

struct A 
{ 
    A() { cout << "A is constructed" << endl; } 
    ~A() { cout << "A is destructed" << endl; } 
}; 

template<typename T> 
void f(T & c) { cout << " non-const parameter" << endl; } 

template<typename T> 
void f(const T & a) { cout << "const parameter" << endl; } 

int main() 
{ 
    f(A()); //passing temporary object! 
} 

输出:

A is constructed
const parameter
A is destructed

的事实函数打印const parameter表明A的寿命得以延长,直到被调用的函数结束后A is destructed

代码在ideone:虽然http://www.ideone.com/2ixA6

+0

不知道理论基础是否非常有说服力,但是,因为无论如何临时都会坚持到表达式结尾(至少直到函数返回),并且不需要任何扩展。 – visitor 2011-02-16 12:34:36

+0

@visitor:编辑并添加更多演示! – Nawaz 2011-02-16 12:41:47

-1

这并不工作:

#include <utility> 
#include <string> 

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 works 
    return 0; 
} 

我猜它是与名称解析。

2

使用“C常量& C”不是“C & C”

你暂时对从make_pair返回不能绑定到你的运营商< <预期的参考,只有一个const引用。