29
votes

I am trying to solve a programming problem that consists of an object (call it Diagram), that contains several parameters. Each parameter (the Parameter class) can be one of several types: int, double, complex, string - to name a few.

So my first instinct was to define my Diagram class as having a vector of template parameters, which would look like this.

class Diagram
{
private:
    std::vector<Parameter<T> > v;
};

This doesn't compile, and I understand why. So, based on the recommendations on this page How to declare data members that are objects of any type in a class, I modified my code to look like:

class ParameterBase
{
public:
    virtual void setValue() = 0;
    virtual ~ParameterBase() { }
};


template <typename T>
class Parameter : public ParameterBase
{
public:
    void setValue() // I want this to be 
                    // void setValue(const T & val)
    {
        // I want this to be 
        // value = val;
    }

private:
    T value;
};

class Diagram
{
public:
    std::vector<ParameterBase *> v;
    int type;
};

I'm having trouble figuring out how to call the setValue function with an appropriate templated parameter. It is not possible to have a templated parameter in the ParameterBase abstract base class. Any help is greatly appreciated.

P.S. I don't have the flexibility to use boost::any.

2
You can't virtually set the parameter to any value, you either need to cast to the appropriate Parameter<T> type or remove the object and create a new oneK-ballo
Don't use a setter, use a constructor, then you can always do v.push_back(new Parameter<My>(my));Gene Bushuyev
Why not just convert them to a common type and convert back when needed? That's how things like this are usually done.KillianDS
@KillianDS I'm not sure I understand what you mean ... Do you mean using void* and casting?endbegin
@endbegin - then you are out of luck, you erased the type information, so you can either use virtual functions (but they must have the same signature), or an ugly unmaintainable if(dynamic_cast<Parameter<My1>*>(base)) ...; else ...Gene Bushuyev

2 Answers

35
votes

You got very close. I added a few bits because they're handy

class ParameterBase
{
public:
    virtual ~ParameterBase() {}
    template<class T> const T& get() const; //to be implimented after Parameter
    template<class T, class U> void setValue(const U& rhs); //to be implimented after Parameter
};

template <typename T>
class Parameter : public ParameterBase
{
public:
    Parameter(const T& rhs) :value(rhs) {}
    const T& get() const {return value;}
    void setValue(const T& rhs) {value=rhs;}    
private:
    T value;
};

//Here's the trick: dynamic_cast rather than virtual
template<class T> const T& ParameterBase::get() const
{ return dynamic_cast<const Parameter<T>&>(*this).get(); }
template<class T, class U> void ParameterBase::setValue(const U& rhs)
{ return dynamic_cast<Parameter<T>&>(*this).setValue(rhs); }

class Diagram
{
public:
    std::vector<ParameterBase*> v;
    int type;
};

Diagram can then do stuff like these:

Parameter<std::string> p1("Hello");
v.push_back(&p1);
std::cout << v[0]->get<std::string>(); //read the string
v[0]->set<std::string>("BANANA"); //set the string to something else
v[0]->get<int>(); //throws a std::bad_cast exception

It looks like your intent is to store resource-owning pointers in the vector. If so, be careful to make Diagram have the correct destructor, and make it non-copy-constructable, and non-copy-assignable.

6
votes

The bellow implementation uses a few C++11 features but you will be able to pick them apart.

#include <vector>
#include <memory>

class Parameter
{
private:
  class ParameterBase {
  public:
    virtual ~ParameterBase() {}
    virtual ParameterBase* copy() = 0;
    virtual void foo() = 0;
  };

  template <typename T>
  class ParameterModel : public ParameterBase {
  public:
    // take by value so we simply move twice, if movable
    ParameterModel(const T& t) : t(t) {}
    ParameterModel(T&& t) : t(t) {}
    void foo() { t.foo(); }
    ParameterModel* copy() { return new ParameterModel(*this); }
  private:
    T t;
  };

public:
  template <typename T>
  Parameter(T&& t) 
    : pp(new ParameterModel< typename std::remove_reference<T>::type >(std::forward<T>(t))) {}

  // Movable and Copyable only
  Parameter(Parameter&&) = default;
  Parameter& operator=(Parameter&&) = default;

  Parameter(const Parameter& other) : pp(other.pp->copy()) {};
  Parameter operator=(const Parameter& other) {
    pp.reset(other.pp->copy());
    return *this;
  };

  // members

  void foo() { pp->foo(); }
private:
  std::unique_ptr<ParameterBase> pp;
};


class Diagram
{
public:
  std::vector<Parameter> v;
  int type;
};

struct X {
  void foo() {}
};

struct Y {
  void foo() {}
};

int main()
{
  Diagram d;
  d.v.emplace_back(X()); // int

  // parameters are copyable and can be reassigned even with different
  // impls
  Parameter p = d.v.back();

  Parameter other((Y()));
  other = p;
  return 0;
}

What does this code do? It hides the fact that we use inheritance to implement parameters from our users. All they should need to know is that we require a member function called foo. These requirements are expressed in our ParameterBase. You need to identify these requirements and add the to ParameterBase. This is basically a more restrictive boost::any.

It is also quite close to what is described in Sean Parent's value semantics talk.