Template accepting partial type names?
Hi all,
I have some questions for template definition:
In the code bellow I could write:
#1: GenEditor<Mul> (&vint, 5);
which compiles fine. But for my understanding Mul is not a typename,
because MUL itself is a template
which needs to have more information to becomes a full type. I expect:
#2: GenEditor<Mul<Var<int>,int> (&vint, 5);
to be correct, but #1 works!
My first question: Is the code #1 correct and is it allways allowed to
give only parts of a template definition as
template parameter? Is this code accepted by most compilers. I
actually run under gcc 4.3.0.
The next question is to simplify my code by generate Objects of class
Editor direct, not indirect by using my GenEditor function template!
As I know, it is allowed to have template constructors in non template
classes, ok.
I can write a constructor for Editor which accepts the arguments like
Editor(Var<T>*, T) but
I am not able to give the needed template parameter Mul or Incr to it.
I can make the complete class Editor
to be a template and than I am able to give the parameter, but this
doubles the generated code for the
complete class, which is not what I would do.
What I want is something like :
Editor ed1<Mul>(&vint, 5);
Any suggestions?
Thanks a lot!
Regards
Klaus
Example Code:
#include <iostream>
using namespace std;
class VarBase {
public:
};
template <class T>
class Var: public VarBase {
private:
T content;
public:
Var(T _i): content(_i) {}
T Get() { return content; }
template <class X, class Y> friend class Incr;
template <class X, class Y> friend class Mul;
};
class OpBase {
public:
virtual void Up()=0;
virtual void Down()=0;
};
template <class VT, class T>
class Incr: public OpBase {
private:
T i;
VT *v;
public:
Incr(VT *vb, T _i): i(_i), v(vb) {}
void Up() { v->content+=i; }
void Down() { v->content-=i; }
};
template <class VT, class T>
class Mul: public OpBase {
private:
T i;
VT *v;
public:
Mul(VT *vb, T _i): i(_i), v(vb) {}
void Up() { v->content*=i; }
void Down() { v->content/=i; }
};
class EditorBase {
public:
virtual void Up()=0;
virtual void Down()=0;
};
class Editor : public EditorBase {
private:
OpBase *i;
public:
//template <template <class, class> class OP, class T, class
I>
Editor( OpBase* _i): i(_i){ }
void Up() { i->Up(); }
void Down() { i->Down(); }
};
template <template <class, class> class OP, class T>
EditorBase* GenEditor(Var<T>* var, T val) { return new Editor(new
OP<Var<T>, T>(var, val)); }
int main() {
Var<int> vint(10);
EditorBase* e=GenEditor<Mul> (&vint, 5);
//Editor e<Mul>(&vint, 5);
cout << "Wert ist:" << vint.Get() << endl;
e->Up();
cout << "Wert ist:" << vint.Get() << endl;
//------------
cout << "Wert ist:" << vint.Get() << endl;
EditorBase* e2=GenEditor<Incr> (&vint, 3);
e2->Up();
cout << "Wert ist:" << vint.Get() << endl;
//-------------
cout << "-----------" << endl;
return 0;
}