是否可以制作自定义运算符以便您可以执行此类操作?
Is it possible to make a custom operator so you can do things like this?
if ("Hello, world!" contains "Hello") ...
注意:这是一个单独的问题,与...
Note: this is a separate question from "Is it a good idea to..." ;)
有几个公开可用的工具可以帮助您.两者都使用预处理器代码生成来创建实现自定义运算符的模板.这些运算符由一个或多个内置运算符和一个标识符组成.
There are a couple publicly available tools to help you out. Both use preprocessor code generation to create templates which implement the custom operators. These operators consist of one or more built-in operators in conjunction with an identifier.
由于这些实际上不是自定义运算符,而只是运算符重载的技巧,因此有一些警告:
Since these aren't actually custom operators, but merely tricks of operator overloading, there are a few caveats:
_
、o
或类似的简单字母数字._
, o
or similarly simple alphanumerics.当我为此目的开发自己的库时(见下文),我遇到了这个项目.以下是创建 avg
运算符的示例:
While I was working on my own library for this purpose (see below) I came across this project. Here is an example of creating an avg
operator:
#define avg BinaryOperatorDefinition(_op_avg, /)
DeclareBinaryOperator(_op_avg)
DeclareOperatorLeftType(_op_avg, /, double);
inline double _op_avg(double l, double r)
{
return (l + r) / 2;
}
BindBinaryOperator(double, _op_avg, /, double, double)
什么开始是纯粹的轻浮练习成为我自己对这个问题的看法.下面是一个类似的例子:
What started as an exercise in pure frivolity became my own take on this problem. Here's a similar example:
template<typename T> class AvgOp {
public:
T operator()(const T& left, const T& right)
{
return (left + right) / 2;
}
};
IDOP_CREATE_LEFT_HANDED(<, _avg_, >, AvgOp)
#define avg <_avg_>
这篇关于你能在 C++ 中制作自定义运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!