我知道 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';
}
一般来说,没有。我可以破解 <-
的这个特定示例通过使用其他运算符。
关于c++ - C++ 中带有特殊字符的自定义运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36115471/