Boost logo

Boost :

Subject: [boost] virtual protected inheritance and default constructors
From: gzp (z.p.gaal_at_[hidden])
Date: 2010-11-30 12:27:12


Hello,

This might be an off-topic question, but there must be here some clever guy
who can answer my question.

class Impl {
public:
        Impl() { std::cout << "j"; } // want to eliminate, but cannot :(
        Impl(int j) { i = j; std::cout << "i"; }
        int i;
};

template<typename TImpl>
class A : virtual protected TImpl {
public:
        void geti() const { std::cout << "gi" << i << "\n"; }
};

template<typename TImpl>
class B : public A<TImpl> {
public:
        void seti(int a) { this->i = a; }
};

class CA : public A<Impl> {
public:
        CA() : Impl(3) { std::cout << "ca " << i;}
};

class CB : public B<Impl> {
public:
        CB() : Impl(2) { std::cout << "cb " << i;}
};

//abuse of interfaces
template<typename TImpl>
void foo( A<TImpl>& p_a ) {
        p_a.geti();
}

template<typename TImpl>
void foo( B<TImpl>& p_a ) {
        p_a.seti( 2 );
}

template<typename TImpl>
void foo2( A<TImpl>& p_a ) {
        p_a.geti();
}

int main( int, char*[] )
{
        CA a;
        std::cout << "\n";
        CB b;
        std::cout << "\n";

        foo(a);
        foo(b);
        foo2(a);
        foo2(b);
        return 0;
}

The basic concept was that: there is a simple implementation class and using
some interfaces (bridge classes) the appropriate function call (foo) can be
ensured using compile time type checking. The implementation might provide
implementation to multiple interfaces (bridge classes) and these interfaces
guarantee the required operation for each (template)functions. The role of
A and B is to provide the interface and bridge it to the implementation. The
only missing part was, how to construct a CA and CB object. They might have
completely different construction parameters and the virtual protected
inheritance partially solved the problem.
BUT the default constructor is always required (VC2008) even tough it gets
never called (I don't want to create any object from A,B (who are missing
these default ctors) but I couldn't tell it to the compiler)
"The declare and don't define" doesn't solve the problem either as the
linker requires the default Impl ctor even though it never gets called.

For example:
impl1: a range iterator for an 1D array: ctor requires the array.begin,
array.end
impl2 a random generator range: ctor requires the random seed

CA: isEmpty, front, popFront
CB: put, mutable front

copy from random range to array is valid (template foo(A,B)), but not the
other way (no template foo(B,A))

Thanks,
Gzp

-- 
View this message in context: http://boost.2283326.n4.nabble.com/virtual-protected-inheritance-and-default-constructors-tp3065825p3065825.html
Sent from the Boost - Dev mailing list archive at Nabble.com.

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk