Being new to template programming, I'm getting lost in a structure I'm trying to build.
class Base;
template <typename T>
class Foo : public Base {
protected:
T mValue;
std::vector<Base> mFooVector; // the idea is to have Foo<T> elements
// of several T types
public:
T value() {
return mValue;
}
void SetValueFromVector() {
mValue = Transform( mFooVector );
// to give you an idea of what awaits below
}
T Transform( std::vector<Base> ) {
// Question deals with what I want to do here
}
/*...*/
}
class Base{
// here, how to declare a virtual or template 'value()'
// that could be instantiated or specialized within Foo?
// Or should I declare a public 'mValue' of some type?
// (see below)
};
In Transform
I would like to call value() from all elements of 'mFooVector' which can be arranged in various type associations. There would be functions, defined elsewhere, that handle all possible practical cases.
But there remains the question of how to call value()
or access mValue
from objects declared as instances of class Base
.
I asked a question yesterday that was only the start of my research - the problem is not the container anymore, since I used polymorphism, but the fact that I need to call the value()
function on instances it contains.
EDIT: In case it helps anyone, here is the way I eventually defined by class. I accepted @PiotrNycz 's answer because it led me really close to my goal, but it was not exactly implementing what I needed.
class Base {
public:
virtual void setValue( &int ) =0;
virtual void setValue( &float ) =0;
virtual void setValue( &double ) =0;
}
template <typename T>
class Foo : public Base {
protected:
T mValue;
std::vector<Base*> mFooVector;
T Transform( std::vector<Base*> );
public:
// this is for use from outside the class
T value() {
return mValue;
}
void SetValueFromVector() {
mValue = Transform( mFooVector );
}
// the three below are only going to be used within 'Transform'
void setValue( int& i ) { i = mValue; }
void setValue( float& f ) { f = (float) mValue; }
void setValue( double& d ) { d = (double) mValue; }
}
// specialization of Transform
template<>
int Foo<int>::Transform( std::vector<Base*> v )
{
// here I only use setValue functions
// if for example I know that first v element is 'float'
float val;
v[0]->setValue( val );
return 3*int(val);
}
// and etc.