Java-like annotations in C++

后端 未结 4 1445
故里飘歌
故里飘歌 2020-12-10 10:30

Is there something like Java\'s annotations in C++ ?

For example, the @Override annotation marks a function that it overrides another function, and if it wouldn\'t,

相关标签:
4条回答
  • 2020-12-10 10:45

    C++0x will have this feature, where you can explicitly specify whether a member function is meant to override a base class' function, use a default implementation generated by the compiler and much more.

    0 讨论(0)
  • 2020-12-10 10:58

    There's nothing in the language for this. The best you could hope for is a compiler-specific option. I'd start by checking the documentation for "pragma" for your compiler.

    0 讨论(0)
  • 2020-12-10 11:03

    There is C++0x, which has the override 'annotation'. Or, if you wanted to achieve more of the Java "interface" like-code that errors if you don't implement methods, you could use an abstract class:

        class Base {
    public:
        virtual void foo() = 0;
    };
    
    class Extended : public Base {
    public:
    
        void foo2() {
            cout << "hi" << endl;
    };
    
    int main() {
        Extended e;
        e.foo();
    }
    

    This will result in a compiler error if you don't override foo in the base class. The issue, however, is that the base class can't have it's own implementation.

    0 讨论(0)
  • 2020-12-10 11:04

    C++11 provides support for generalized attributes, which can be seen as superset of Java annotations, as they can be applied not just to variables/functions, but also to statements, for example. But C++11 defines only syntax for generalized attributes, not means for user to define them.

    This article gives good overview of generalized attributes: http://www.codesynthesis.com/~boris/blog/2012/04/18/cxx11-generalized-attributes/

    GCC supports this feature from version 4.8, according to: http://gcc.gnu.org/projects/cxx0x.html

    To implement support for user-defined attributes, compiler plugins are promising, especially based on high-level language integration, like https://fedorahosted.org/gcc-python-plugin/

    0 讨论(0)
提交回复
热议问题