Overload the 'space' operator in C++?
I have a little bit of experience in C++. I know how to overload the plus sign and what not, but would like to overload the space operator.
For example:
MyObject obj();
result = obj - foo; // This would be treated as a normal '-' operation.
result = obj-foo; // This would invoke code which throws an assert at runtime
This would allow me to enforce certai开发者_运维知识库n style guidelines I'm trying to set forth for my team.
There is no space operator in C++. Whitespace is not significant in most cases, there is no difference from a parsing point of view between
a-b
and
a - b
Which I'm happy for.
Note: there are some corner cases (nested templates spring to mind) where it actually matters, but that's more of an artifact of the grammar than indications of the whitespace being active as an "operator", in my opinion.
Bjarne Stroustrup did at one time suggest allowing overloading of whitespaces [PDF]. But seeing as this article was published on April 1st he may not have been 100% serious...
The article is worth a read though.
There is no such item as the whitespace operator. In general in C++ whitespace is irrelevant and doesn't cause functionality differences in the program, hence there's nothing to overload.
What you're looking for is a static analysis tool for C++. Something akin to StyleCop for C++. Unfortunately I don't have a lot of experience in this area and can't recommend a specific program. Likely someone else on this thread will be able to though.
Sorry, not possible.
Instead look at code formatters - there are a few for every popular IDE (for example checkstyle for eclipse), or you can setup pre-commit hook in your version control system server, that checks if code before and after formattting is the same, and if not, it returns error instead of allowing to commit the code.
It's not possible. Space is not an operator. If you want to enforce style, use static code analysis tools and talk to your team members. Try cpplint or something similar.
If you want to enforce style guidelines, obtain a tool or application that can identify violations of style. A tool that can do this is Klocwork. There are probably smaller and simpler tools out there.
Worst case, write your own.
I'd recommend a look at Guy Steele's new HPC language: Fortress. It allows the overloading of the juxtaposition operator. There's also a blog post covering this aspect here. It's not going to help you with formatting, but it's rather funky. (Haskell and ML also use juxtaposition to apply functions).
精彩评论