boost::addable2的使用-为什么从operator+返回的结果是相反的
usage of boost::addable2 - why the returned result from operator+ is reversed
#include <iostream>
#include <string>
#include "boost/operators.hpp"
using namespace std;
class simple_string : private boost::addable1<simple_string,
boost::addable2<simple_string, const char*> >
{
public:
simple_string() : m_str("Default")
{}
explicit simple_string(const char* s) : m_str(s)
{}
simple_string(const simple_string& rhs) : m_str(rhs.m_str)
{}
simple_string operator+=(const simple_string& rhs)
{
m_str += rhs.m_str;
return *this;
}
simple_string operator+=(const char* rhs)
{
this->operator+=(simple_string(rhs));
return *this;
}
friend ostream& operator<<(ostream& os, const simple_string& si)
{
os << si.m_str;
return os;
}
private:
string m_str;
};
int main(void)
{
simple_string s1;
simple_string s2(s1);
cout << "[before] s2: " << s2 << endl;
s2 += s1;
cout << "s2 += s1: " << s2 << endl;
simple_string s3 = s1 + s2;
cout << "s3: " << s3 << endl;
simple_string s4 = s3 + "Why";
simple_string s5 = "Now" + s3;
cout << "s4: " << s4 << endl;
cout << "s5: " << s5 << endl;
cout << "Now" + simple_string() << endl;
return 0;
}
~/Documents/C++/boost $ g++ -o p123 p123.cpp
~/Documents/C++/boost $ ./p123
[before] s2: Default
s2 += s1: DefaultDefault
s3: DefaultDefaultDefault
s4: DefaultDefaultDefaultWhy
s5: DefaultDefaultDefaultNow
DefaultNow
~/Documents/C++/boost $
问题>为什么生成的operator+(const char*, const simple_string&)
没有返回正确的结果?
例如,s5
的预期结果应该是s5: NowDefaultDefaultDefault
, "Now" + simple_string()
的结果应为NowDefault
问题是,对于字符串operator+
是不可交换的,但boost实现假设它是。详情请参阅http://www.boost.org/doc/libs/1_32_0/libs/utility/operators.htm#symmetry的对称说明。
编辑:在阅读实际的boost代码,我认为我错了。您不能对operator+
不可交换的类使用boost操作符生成,因为这是boost中的隐式假设。你必须自己实现它。
基于(我相信)错误阅读文档的原始答案:
您可以强制执行不假设对称的可能效率较低的代码,如下所示:
...if your code relies on the function signature or a strict symmetric behaviour, you should set BOOST_FORCE_SYMMETRIC_OPERATORS in your user-config. This will force the NRVO-friendly implementation to be used even for compilers that don't implement the NRVO.
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 有没有办法修改'operator->',以便'z->im'返回复数的虚部
- 无法赋值,因为函数'operator[]'返回常量值
- 迭代器的标准接口::operator*返回的比T&和std::p air更多
- 对简单的帐户检查程序有问题?程序返回编译错误,指出"no match for 'operator||' unsure of how to fix?"
- C++11 标准中的哪些条款允许我消除下面“A::operator-()”中“返回”语句中的“A”
- 为什么返回类型 std::reverse_iterator::operator[] 未指定
- 如何为 operator[] 指定返回类型
- 为什么 QMap::operator[](const Key & key) 按值返回?
- 从std::vector::operator[]获取返回地址做什么
- 重载 operator= 时返回引用和值有什么区别?
- boost::addable2的使用-为什么从operator+返回的结果是相反的
- 如果我想使类不可复制,"operator="返回类型是否重要?
- QImage::operator==对于具有相同内容的图像是否返回false ?
- 声明一个接受并返回` `流` `的函数有什么用?而不是重载operator<<
- 希望std::string::operator[]可以返回unsigned char
- 执行operator new的任何实现都返回指向大小为零的数组的保护页的指针
- C++11 std::string::operator[]是否返回null终止的缓冲区
- std::vector::operator[]返回的引用可以使用多长时间?
- 是否可以在重载中使用修改后的返回引用,例如"int &operator[]"?