Can you make custom operators in C++?

前端 未结 6 1927
盖世英雄少女心
盖世英雄少女心 2020-12-01 00:24

Is it possible to make a custom operator so you can do things like this?

if (\"Hello, world!\" contains \"Hello\") ...

Note: this is a sepa

6条回答
  •  春和景丽
    2020-12-01 00:44

    Technically, no. That is to say, you can't extend the set of operator+, operator-, etcetera. But what you're proposing in your example is something else. You are wondering if there is a definition of "contains" such that string-literal "contains" string-literal is an expression, with non-trivial logic (#define contains "" being the trivial case).

    There are not many expressions that can have the form string-literal X string-literal. This is because string literals themselves are expressions. So, you're looking for a language rule of the form expr X expr. There are quite a few of those, but they're all rules for operators, and those don't work on strings. Despite the obvious implementation, "Hello, " + "world" is not a valid expression. So, what else can X be in string-literal X string-literal ? It can't be a expression itself. It can't be a typename, a typedef name or a template name. It can't be a function name. It can really only be a macro, which are the only remaining named entities. For that, see the "Yes (well, sort of)" answer.

提交回复
热议问题