There is a lot of template intricacies I don't understand so hopefully someone can help me out. What I want to do is:
class A
{
public:
A( int &num ) : _num(num) {}
private:
int &_num;
};
template< typename T, typename Base >
class Glue : public Base
{
public:
Glue() {}
};
int g_num = 0;
class B : public Glue<B,A>
{
public:
B() : A(g_num) {}
};
This is obviously a contrived exmaple but assume that Glue has some useful functionality to automate a lot of stuff in a type-safe way. The compiler can't construct A through Glue because no default constructor exists but it will try anyways and come up with a linker error if you remove the explict call to A's constructor. And the compiler won't allow the A contstructor in class B's constructor because it will then be trying to construct A twice.
So what I was thinking what I needed was to add a constructor to class Glue<B,A> that looks like Glue<B,A>::Glue( int &num ) : A(num) {}
So in trying to do this I modified the code to be:
class A
{
public:
A( int &num ) : _num(num) {}
private:
int &_num;
};
template< typename T, typename Base >
class Glue : public Base
{
public:
Glue() {}
int GlueFunction() const { return 3; }
};
class B;
template<>
class Glue<B,A> : public A
{
public:
Glue( int &num ) : A(num) {}
};
int g_num = 0;
class B : public Glue<B,A>
{
public:
B() : Glue<B,A>(g_num) { int blah = GlueFunction(); }
};
But in doing so C++ assumes I want to fully specialize the entire class even though I just want to insert one function. Thus doing this requires copy and pasting all the code from Glue for any Glue where Base doesn't have a default constructor.
The other solution I thought of was to go to:
class A
{
public:
A( int &num ) : _num(num) {}
private:
int &_num;
};
template< typename T, typename Base >
class Glue
{
public:
typedef Base Super;
Glue() {}
int GlueFunction() const { return 3; }
};
int g_num = 0;
class B : public A, public Glue<B,A>
{
public:
B() : A(g_num) { int blah = GlueFunction(); }
};
But this adds an extra step for things to go wrong, requires a change to a large number of existing classes, and the engineers here, myself included, like to stay away from multiple inheritence as it tends to complicate things.