Spamdark
Spamdark

Reputation: 1391

Best way to pass multiple data types

I'm programming a plugin framework, the plugin is supposed to pass data to the application, I created a queue where the plugin puts the data, but I want that the plugin can pass multiple data types (int, bool, char, ...) and not only one.

Any ideas or any good way to do that?

Upvotes: 2

Views: 389

Answers (3)

statueuphemism
statueuphemism

Reputation: 664

Use templates and other generic programming techniques as part of your design.

Here's a starter on templates: http://www.cplusplus.com/doc/tutorial/templates/

Using boost any is most recommended, but an alternative that I think is better from a design perspective than the current accepted answer (if you want to minimize dependencies) is the following very simple implementation of a template wrapper that accepts and returns any type:

class IAnyType {}

template <class T>
class AnyType : public IAnyType
{
private:
    T value_;
public:
    AnyType(T value) : value_(value) {}

    void set(T value) { value_ = value; }

    T get() { return value_; }
};

Then, just make your queue hold IAnyType objects and store all arguments inside an AnyType object before adding it to the queue. You could certainly spruce this up a bit by overloading various assignment operators and make usage even simpler.

Upvotes: 1

Kevin
Kevin

Reputation: 2730

You can use chars and cast them to just about anything. For the data types you can't "get to" with simple casting I suggest using memcpy().

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726967

If using the boost library is an option, I would highly recommend using boost::any:

boost::any a(1234567);
boost::any b(12.3456);
boost::any c(12345LL);
boost::any d(true);

Upvotes: 5

Related Questions