简体   繁体   中英

Java-like annotations in C++

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, it would give an error at compile time.

I am looking for something like this in C++.

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/

C++0x将具有此功能,您可以在其中明确指定成员函数是否旨在覆盖基类的函数,使用编译器生成的默认实现等等。

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.

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.

I'm not sure what JAVA provides in general, but for the specific functionality you mentioned, C++ has the override keyword:

class Derived : public Base {
    void foo() override { ... }
};

You'll get a helpful compiler error message if Base doesn't have a corresponding virtual void foo() .

Another functionally-similar keyword is final , which can be used to say that the function is an override that can't be further overridden in further-derived classes. (The same keyword can be used to say a class can't be derived from).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM