Anonymous user
Delegates: Difference between revisions
no edit summary
No edit summary |
No edit summary |
||
Line 189:
=={{header|C++}}==
Delegates in the C# or D style are available in C++ through std::tr1::function class template. These delegates don't exactly match this problem statement though, as they only support a single method call (which is operator()), and so don't support querying for support of particular methods.
#include <tr1/memory>
#include <string>
#include <iostream>
#include <tr1/functional>
using namespace std;
using namespace std::tr1;
using std::tr1::function;
// interface for all delegates
class IDelegate
{
public:
virtual
};
{▼
return "default implementation";▼
//interface for delegates supporting thing
class IThing
{
public:
virtual ~IThing() {}
virtual std::string Thing() = 0;
};
// Does not handle Thing
class DelegateA : virtual public IDelegate
{
};
// Handles Thing
class DelegateB : public IThing, public IDelegate
{
std::string Thing()
Line 219 ⟶ 229:
}
};
class Delegator
{
Line 225 ⟶ 235:
std::string Operation()
{
if(Delegate) //have delegate
if
//delegate provides IThing interface
return
▲ return "default implementation";
}
};
int main()
{
Delegator delegator;
// No delegate
std::cout << delegator.Operation() << std::endl;
// Delegate doesn't handle "Thing"
delegator.Delegate = delegateA;
std::cout << delegator.Operation() << std::endl;
// Delegate handles "Thing"
delegator.Delegate = delegateB;
std::cout << delegator.Operation() << std::endl;
▲}</lang>
/*
Prints:
default implementation
default implementation
delegate implementation
*/
}
</lang>
=={{header|Common Lisp}}==
{{trans|Python}}
|