gpt4 book ai didi

c++ - 模板运算符 << 重载和 make_pair

转载 作者:搜寻专家 更新时间:2023-10-31 00:46:33 25 4
gpt4 key购买 nike

我在使用模板成员重载运算符和使用 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<< 的任何想法在第二种情况下?

最佳答案

operator<<的参数应该是 const :

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

因为 std::make_pair返回一个不能绑定(bind)到非常量参数的临时对象。但是临时对象可以绑定(bind)到 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

编辑:

当然,上面的输出仅仅说明了temporary被绑定(bind)到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

事实A is destructed在函数打印出 const parameter 之后证明A的生命周期延长到被调用函数结束!

ideone 的代码:http://www.ideone.com/2ixA6

关于c++ - 模板运算符 << 重载和 make_pair,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5016195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com