vendredi 28 août 2015

Perform context specific action with templated variable type

I want to have multiple contexts that are instanciated somewhere else. Now we want to set key-value variables to some value of type T, context-dependent.

A variable class is a handle to set an arbitrary type to some value.

Each context handles the variable setting differently (namely these are graphics backends.) For that, the Context::magically_set method could be specialized for each supported T.

But each context handles each supported T differently.

Here's my "working" code if virtual member functions could be templated:

class Context {
    template<typename T>
    virtual void magically_set(const T &value);
};

class ContextA : public Context {
    template<typename T>
    void magically_set(const std::string &name, const T &value) override;
    // somewhere else: T-specific implementation for this context.
};

class ContextB : public Context {
    template<typename T>
    void magically_set(const std::string &name, const T &value) override;
    // somewhere else: T-specific implementation for this different context.
};

template<typename T>
class Variable {
    Variable(std::string name, Context *context)
        : name{name}, context{context} {}

    void set(const T &value) {
        this->context->magically_set(this->name, value);
    }

    std::string name;
    Context *context;
};

and the usage:

ContextB ctx_b;
Variable<float> test{"bla", ctx_b};
test.set(0.1337f);

How can I make this work? I can use anything supported by c++14, but no boost.

Aucun commentaire:

Enregistrer un commentaire