能够超载它是非常有用的.C++中的operator并返回对象的引用.
你可以超载operator->,operator*但不能operator.
这有技术原因吗?
我发现使用C++ STL方法进行简单的集合操作非常笨重.例如,要找到两组之间的差异:
std::set<int> newUserIds;
set_difference(currentUserIds.begin(), currentUserIds.end(), mPreviousUserIds.begin(), mPreviousUserIds.end(), std::inserter(newUserIds, newUserIds.end()));
std::set<int> missingUserIds;
set_difference(mPreviousUserIds.begin(), mPreviousUserIds.end(), currentUserIds.begin(), currentUserIds.end(), std::inserter(missingUserIds, missingUserIds.end()));
mPreviousUserIds = currentUserIds;
Run Code Online (Sandbox Code Playgroud)
boost是否提供了一组替代类,可以将上面的示例缩小为:
set_type<int> newUserIds = currentUserIds.difference(mPreviousUserIds);
set_type<int> missingUserIds = mPreviousUserIds.difference(currentUserIds);
Run Code Online (Sandbox Code Playgroud)
(类似于Qt中的QSet,它operator-以这种方式覆盖.)
我遇到了以下用例,但我找不到合适的解决方案.有没有办法用条件来代替字符串"<"或">" <或>在if条件?
例:
string condition = "<";
if (10 condition 8) // Here I want to replace condition with <
{
// Some code
}
Run Code Online (Sandbox Code Playgroud)
我不想这样做:
if ("<" == condition)
{
if (10 < 8)
{
}
}
else if (">" == condition)
{
if (10 > 10)
{
}
}
Run Code Online (Sandbox Code Playgroud)
而且我的病情会在运行期间发生变化.如果存在于上面,我只是在寻找一种简单的方法.
使用案例:用户将提供如下查询:
input: 10 > 9 => output: true
input: 10 < 7 => output: false
Run Code Online (Sandbox Code Playgroud)
基本上我需要解析这个查询,因为我将这3个单词(10,>,9)作为字符串,并且我想以某种方式将字符串">"或"<"转换为实际符号>或<.
在 C++ 中,我可以通过typedef语句定义现有类型的别名。但是可以为操作员创建别名吗?具体来说,我想选择一些 Unicode 符号并为<<操作符创建一个别名。
我想使用例如“垂直四点” U+205E:
cout
? endl ? "filename: " ? cfgfilename
? endl ? "message: " ? e.what()
? endl ? "exception id: " ? e.id
? endl ? "byte position: " ? e.byte ;
Run Code Online (Sandbox Code Playgroud)
取而代之的是:
cout
<< endl << "filename: " << cfgfilename
<< endl << "message: " << e.what()
<< endl << "exception id: " << e.id
<< endl << "byte position: " << e.byte ;
Run Code Online (Sandbox Code Playgroud)
如果不能使用四点字符,但使用其他一些符号,它也可以是一个选项(尽管比基本 ASCII 有更多选项会更好)。