简体   繁体   中英

Void pointer in C++

I learned that templates are the void* equivalents in C++. Is this true?

I have this issue in polling "events" off some procedure, when I have an EventType variable and I may also need to pass raw data that is related to that event.

struct WindowEvent {
    enum Type {WINDOW_SIZE_CHANGE, USER_CLICK, ...};

    void* data;
};

The user may then cast data to the necessary type, depending on the event type.

Is this approach okay in C++? Are there any better approaches?

In C, which generally lacks support for polymorphism, void* pointers can be used to accept data of any type, along with some run-time representation of the actual type, or just knowledge that the data will be casted back to the correct type.

In C++ and other languages with support for polymorphism one will generally instead use either dynamic polymorphism (classes with virtual functions) or static polymorphism (function overloads and templates).

The main difference is that the C approach yields dynamic (run time) manual type checking, while the C++ approaches yield mostly static (compile time) and fully automated type checking. This means less time spent on testing and hunting down silly easily preventable bugs. The cost is more verbose code, and that means that there's a code size offset somewhere, under which the C approach probably rules for productivity, and above which the C++ approaches rule.

"I learned that templates are the void equivalents in C++. Is this true?"*

No - Templates maintain type safety

"Is this approach okay in C++?"

No

"Are there any better approaches?"

Depending on the use case one could use (for example)

class EventData {
   public:
      virtual int getData() = 0;
};

And then use the appropriate inherited class. Perhaps using smart pointers.

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