C++静态运算符重载
是否可以在静态上下文中重载 C++ 类运算符?例如
class Class_1{ ... }
int main()
{
Class_1[val]...
}
Is it possible to overload C++ class operators in the static context? e.g.
class Class_1{ ... }
int main()
{
Class_1[val]...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您正在寻找使用内置运算符的元编程:这样的事情是不可能的 - 内置运算符对运行时值进行操作,而不是对编译时值进行操作。
您可以使用
boost::mpl
为此,不要使用内置运算符,而是使用其模板,例如at
表示op[]
、plus
表示op+
等。If you are looking for metaprogramming using the built-in operator: Such a thing isn't possible - the built-in operators operate on runtime values, not on compile time values.
You may use
boost::mpl
for that, and instead of using the built-in operators, use its templates, likeat
forop[]
,plus<a, b>
forop+
etc.我不相信这是可能的,尽管我在这方面可能是错的。我想问一下你为什么要这样做。也许您只需要在整个应用程序中使用一个实例,而不是对类而不是实例执行操作?在这种情况下,您可能应该使用单例模式。
I don't believe it's possible, though I could be wrong on this front. I'd like to ask why you'd want to do this though. Rather than performing operations on a class instead of instances, perhaps you just require one instance throughout your application? In this case, you should probably be using the singleton pattern.
如果您的意思是运算符对类进行操作,则否。这没有意义,就像说
operator +
可以对int
或double
进行操作一样代码>.运算符是函数的语法糖,它们对变量(值)而不是类型进行操作。If you mean the operator operates on a class, the No. That does not make sense, it is like saying
operator +
may operator onint
ordouble
. Operators are syntactic sugar for functions and they operate on varibles(values) not types.不可以,运算符不能是类的静态成员。请改用常规静态函数。
No, operators cannot be static members of a class. Use a regular static function instead.
从 C++23 开始,可以重载 静态
operator()
。至于其他运营商:编译器使用 __cpp_static_call_operator 表示支持此功能。
As of C++23, it's possible to overload static
operator()
. As for other operators:A compiler indicates support for this feature with
__cpp_static_call_operator
.