相关疑难解决方法(0)

二元运算符重载,隐式类型转换

class my_bool {
  private:
    bool value;
  public:
    my_bool(bool value) : value(value) {}
    explicit operator bool() { return value };

    friend my_bool operator==(const my_bool & instance_1, const my_bool & instance_2);
    friend my_bool operator&&(const my_bool & instance_1, const my_bool & instance_2);

};

void main(){
  my_bool a = true;
  bool b = false;

  if(a == b){
    // do something
  }

  if(a && b){
    // do something 
  }
}
Run Code Online (Sandbox Code Playgroud)

我刚刚在这里创建了一个关于我的问题的类似主题二元运算符重载; 隐式类型转换.我可以删除它,因为它对我遇到的问题不够明确.

为什么这样operator==可以正常工作并operator&&导致含糊不清?我该如何解决这个问题?我当然可以写下两个operator&&(bool,my_bool),( …

c++

3
推荐指数
1
解决办法
124
查看次数

在编译时检查三向比较运算符的支持

我想operator <=>根据当前版本的编译器及其命令行选项是否支持在我的代码中有条件地启用重载。例如,我希望将以下代码编译为 C++14、17 和 20(这基本上是我之前提出的问题的解决方案的续集):

#define SPACESHIP_OPERATOR_IS_SUPPORTED 1 // <--- i want this to be automatic

#if SPACESHIP_OPERATOR_IS_SUPPORTED
#include <compare>
#endif

template <int N> struct thing {
    // assume an implicit conversion to a "math-able" type exists:
    operator int () const { return 0; }
    // define a set of comparison operators for same N on rhs:
    bool operator == (const thing<N> &) const { return true; }
    bool operator != (const thing<N> &) const { …
Run Code Online (Sandbox Code Playgroud)

c++ portability spaceship-operator c++14 c++20

3
推荐指数
1
解决办法
110
查看次数

标签 统计

c++ ×2

c++14 ×1

c++20 ×1

portability ×1

spaceship-operator ×1