2011-02-16 52 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引用。