問題描述
是否可以制作自定義運(yùn)算符以便您可以執(zhí)行此類操作?
Is it possible to make a custom operator so you can do things like this?
if ("Hello, world!" contains "Hello") ...
注意:這是一個(gè)單獨(dú)的問題,與...
Note: this is a separate question from "Is it a good idea to..." ;)
推薦答案
是的!(嗯,有點(diǎn))
有幾個(gè)公開可用的工具可以幫助您.兩者都使用預(yù)處理器代碼生成來創(chuàng)建實(shí)現(xiàn)自定義運(yùn)算符的模板.這些運(yùn)算符由一個(gè)或多個(gè)內(nèi)置運(yùn)算符和一個(gè)標(biāo)識符組成.
Yes! (well, sort of)
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.
由于這些實(shí)際上不是自定義運(yùn)算符,而只是運(yùn)算符重載的技巧,因此有一些警告:
Since these aren't actually custom operators, but merely tricks of operator overloading, there are a few caveats:
- 宏是邪惡的.如果你犯了一個(gè)錯(cuò)誤,編譯器在追蹤問題方面幾乎毫無用處.
- 即使您正確使用了宏,如果您在使用運(yùn)算符或定義操作時(shí)出現(xiàn)錯(cuò)誤,編譯器也只會稍微提供一些幫助.
- 您必須使用有效標(biāo)識符作為運(yùn)算符的一部分.如果您想要更像符號的運(yùn)算符,您可以使用
_
、o
或類似的簡單字母數(shù)字.
- Macros are evil. If you make a mistake, the compiler will be all but entirely useless for tracking down the problem.
- Even if you get the macro right, if there is an error in your usage of the operator or in the definition of your operation, the compiler will be only slightly more helpful.
- You must use a valid identifier as part of the operator. If you want a more symbol-like operator, you can use
_
,o
or similarly simple alphanumerics.
當(dāng)我為此目的開發(fā)自己的庫時(shí)(見下文),我遇到了這個(gè)項(xiàng)目.以下是創(chuàng)建 avg
運(yùn)算符的示例:
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)
IdOp
什么開始是純粹的輕浮練習(xí)成為我自己對這個(gè)問題的看法.下面是一個(gè)類似的例子:
IdOp
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_>
主要區(qū)別
- CustomOperators 支持后綴一元運(yùn)算符
- IdOp 模板使用引用而不是指針來消除對免費(fèi)存儲的使用,并允許對操作進(jìn)行完整的編譯時(shí)評估
- IdOp 允許您輕松地為同一個(gè)根標(biāo)識符指定多個(gè)操作
這篇關(guān)于你能在 C++ 中制作自定義運(yùn)算符嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!