Cas*_*ton 6 c++ operator-overloading
我希望能够写作
if (3 <= X <= 10)
{
}
else if (20 < X < 100)
{ //...etc
Run Code Online (Sandbox Code Playgroud)
在C++中并正确评估它.我知道你可以用Python做到这一点,我认为这是表达条件的一种非常易读的方式.
我不想写:
if (3 <= X && X <= 10) //etc.
Run Code Online (Sandbox Code Playgroud)
我怎么能用C++做到这一点?可能吗?什么会超载运营商的样子?如果没有,你能解释为什么不可能吗?
Pio*_*ycz 11
你确定需要这个吗?
[UPDATE]
过了一会儿,我想到了一个甚至看起来并不完全疯狂的想法;)
你需要从包装第一个元素开始:
int main() {
int x = 134, y = 14;
if (IntComp(7) <= x <= 134)
{
std::cout << "Hello ";
}
if (IntComp(134) > y > 12)
{
std::cout << "world!";
}
}
Run Code Online (Sandbox Code Playgroud)
这里的魔力:
class IntComp {
public:
IntComp(int x, bool result = true) : value(x), result(result) {}
IntComp operator <= (int x) const
{
return IntComp(x, result && value <= x);
}
IntComp operator > (int x) const
{
return IntComp(x, result && value > x);
}
operator bool() const { return result; }
private:
int value;
bool result;
};
Run Code Online (Sandbox Code Playgroud)
你不能用C++做到这一点.你必须把它分成两个独立的操作:
if (3 <= X && X <= 10)
{
...
}
else if (20 < X && X < 100)
{
...
}
Run Code Online (Sandbox Code Playgroud)
就个人而言,我认为所有这些运营商重载解决方案都有点过度设计.相反,两个简单的功能模板怎么样?
template<typename A, typename B, typename C>
bool ordered(const A& a, const B& b, const C& c)
{
return (a <= b) && (b <= c);
}
template<typename A, typename B, typename C>
bool between(const A& a, const B& b, const C& c)
{
return (a < b) && (b < c);
}
void foobar(int X)
{
if (ordered(3, X, 10))
{
}
else if (between(20, X, 100))
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1345 次 |
最近记录: |