【问题标题】:custom operators with special characters in c++c++中带有特殊字符的自定义运算符
【发布时间】:2016-03-20 15:10:00
【问题描述】:

我知道自定义运算符不受 C++ 官方支持。 而且我已经知道this 来定义自定义运算符。 但是由于这似乎不适用于包含特殊字符的自定义运算符,所以我想知道是否有任何安全的方法或技巧可以在 c++ 中创建具有特殊字符(如 <-#)的自定义运算符

【问题讨论】:

  • 在您的特定示例中,您可以通过重载 <- 运算符来做一些粗暴的事情。但总的来说,没有。
  • 为什么不重载现有的运算符?真的没有现有的运营商可以做类似你想做的事情吗?
  • 那么绝对没有办法?

标签: c++ c++11 macros operator-overloading


【解决方案1】:
struct A {
  int x;
};

template<class T>
struct dashed {
  T t;
  template<class U>
  operator U()&&{ return -std::move(t); }
};

template<class T>
dashed<T> operator-(T&& t){return {{std::forward<T>(t)}};}

template<class T>
A& operator<( A& lhs, dashed<T> rhs ) {
  lhs.x = rhs.t.x;
  return lhs;
}

int main() {
  A a{1}, b{2};
  std::cout << a.x << '\n';
  a <- b;
  std::cout << a.x << '\n';
}

live example.

一般来说,不会。我只是可以通过使用其他运算符来破解&lt;-这个特定示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2020-08-13
    • 1970-01-01
    相关资源
    最近更新 更多