Can the new Clang Objective-C literals be redirected to custom classes?

后端 未结 2 932
小蘑菇
小蘑菇 2020-11-30 03:17

Although the overloading of @ begins to tread on dangerous territory, I love the addition of the new Objective-C literals in Clang 3.1. Unfortunately the new li

2条回答
  •  粉色の甜心
    2020-11-30 04:05

    The comments have it all correct, but just to summarize:

    • No.

    The meanings of Apple's @{}, @[], and @"" literals are hard-coded into Clang. You can see it here: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/NSAPI.cpp?view=markup It's all fairly modular, meaning that it wouldn't be hard for a Clang hacker to add her own literal syntax... but "modular" doesn't mean "accessible from the outside". Adding a new syntax or even redirecting the existing syntax to new classes would definitely require rebuilding Clang yourself.

    Here's a blog post about adding NSURL literals to Clang by hacking on its internals: http://www.stuartcarnie.com/2012/06/llvm-clang-hacking-part-3.html (Thanks @Josh Caswell)


    If you're willing to use Objective-C++ with C++11 extensions, you can has "user-defined literals", which allow you to write things like

    NSURL *operator ""URL (const char *s) { return [NSURL URLWithString: @(s)]; }
    
    int main() {
        ...
        NSURL *myurl = "ftp://foo"URL;
        ...
    }
    

    This was mentioned in the comments on Mike Ash's blog. http://www.mikeash.com/pyblog/friday-qa-2012-06-22-objective-c-literals.html But this doesn't look very Objective-C-ish (or very C++ish!), and it works only with an Objective-C++11 compiler, and in general please don't do this. :)

提交回复
热议问题