Class Template delegating

Description
Headers
Reference
Synopsis
Class Template delegating
Function Template set_delegate
Example

Description

The class template delegating provides support for dynamic inheritance through delegation. Deriving from delegating<Interface> yeilds a class which implements the interface Interface by delegating to an object specified at runtime. A class may derive from several specializations of delegating, thereby implementing multiple interfaces through delegation.

Headers

<boost/interfaces/delegation.hpp>

Reference

Synopsis

namespace boost { namespace interfaces {

template<typename Interface>
class delegating {
protected:
    template<typename T>
    void set(T* t);
};

template<typename Interface, typename Delegating, typename T>
void set_delegate(Delegating& d, T* t);

} } // End namespace boost::interfaces

Class Template delegating

Template parameters
Interface-

An interface defined using the Interface Definition Language (IDL).

delegating::set

Template parameters
T-

A class which implements Interface.

template<typename T>
void set(T* t);

Specifies an object to which invocations of Interface member functions through this instance of delegating are to be directed. Never throws.

Function Template set_delegate

Template parameters
Interface-

An interface defined using the Interface Definition Language (IDL). This parameter must be specified explicitly.

Delegating-

A class deriving from delegating<Interface>.

T-

A class which implements Interface.

template<typename Interface, typename Delegating, typename T>
void set_delegate(Delegating& d, T* t);

Specifies an object to which invocations of Interface member functions through object d are to be directed. Never throws.

set_delegate is able to access the object d outside the scope of the class Delegating only if Delegating has declared the class boost::interfaces::access as a friend; otherwise, invoking set_delegate yields a compile-time error.

Example

// Pseudocode:
interface IAnimal {
    void speak();
};

struct Sheep {
    void speak() { std::cout << "Baaaah\n"; }
};

struct Cow {
    void speak() { std::cout << "Moooo\n"; }
};

struct Delegator : delegating<IAnimal> { 
    friend class boost::interfaces::access;
};

int main()
{
    Delegator d;
    Sheep     s;
    Cow       c;
    d.speak();                    // Undefined behavior: delegate null
    set_delegate<IAnimal>(d, &s);
    d.speak();                    // Prints "Baaaah"
    set_delegate<IAnimal>(d, &c);
    d.speak();                    // Prints "Moooo"
}

Sha'arei Tefila, an Orthodox Shul (Synagogue) in Salt Lake City, Utah Chabad Lubavitch of Utah