c++ - C++ 中带有特殊字符的自定义运算符

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

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

最佳答案

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 .

一般来说,没有。我可以破解 <-这个特定示例通过使用其他运算符。

关于c++ - C++ 中带有特殊字符的自定义运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36115471/

相关文章:

c++ - 如何在 C++ 中简化多个 if-else-if 语句

c++ - 什么可以阻止 C++ 中的堆栈展开过程?

c++ - incredibuild 不使用其他代理

c++ - 类中的 static const std::array

c++ - 如何挑出发送给仅采用可变参数的宏的第一个参数

macros - 将宏的参数字符串化为 unicode

c - 宏中的双斜线注​​释替换

c++ - 为什么我重载的 << 运算符不工作?

c++ - 使用 shared_ptr 和 glutInit 导致段错误

c++ - std::bind 和/或 std::forward 的语义