टेम्पलेट्स का एक विकल्प सी ++ 11 के साथ लैम्ब्डा क्लोजर का उपयोग करना है। मेरी वरीयता यहाँ है।
// in header file
IClass * MyFunctionThatDoesStuff(const IParams & interface_params,
std::function<IClass * (const IParams & interface_params)> cls_allocator);
// in source file
IClass * MyFunctionThatDoesStuff(const IParams & interface_params,
std::function<IClass * (const IParams & interface_params)> cls_allocator) {
// Some processing. Perhaps the interface_params are generated
// inside this function instead of being passed to it.
IClass * mCls = cls_allocator(interface_params);
// Do whatever with mCls
return mCls;
}
// Somewhere else in the code.
{
Param1Type param1 = whatever1;
Param2Type param1 = whatever2;
// param1, param2, etc. are parameters that only
// SomeClsDerivedFromIClass constructor knows about. The syntax ¶m1
// achieves the closure.
// interface_param1 is common to all classes derived from IClass.
// Could more than one parameter. These parameters are parameters that
// vary from different calls of MyFunctionThatDoesStuff in different
// places.
auto cls_allocator =
[¶m1, ¶m2](const IParams & interface_params)->IClass * {
return new SomeCls1DerivedFromIClass(interface_params,
param1, param2);
};
IClass * mCls = MyFunctionThatDoesStuff(interface_params,
cls_allocator);
}
// Somewhere else in the code again.
{
ParamXType paramX = whateverX;
ParamYType paramY = whateverY;
auto cls_allocator =
[¶mX, ¶mY](const IParams & interface_params)->IClass * {
return new SomeCls2DerivedFromIClass(interface_params,
paramX, paramY);
};
IClass * mCls = MyFunctionThatDoesStuff(interface_params,
cls_allocator);
}
ऊपर कोड विचार एक त्वरित बिल्डर पैटर्न या कुछ कारखाने पैटर्न बदलाव के लिए अच्छी तरह से काम करता है। लैम्ब्डा मूल रूप से एक कारखाना विधि है। इसे और भी गतिशील बनाने के लिए आप पैरामीटर टाइपिंग के लिए ऑटो का उपयोग कर सकते हैं। कुछ इस तरह।
auto * MyFunctionThatDoesStuff(const auto & interface_params,
std::function<auto * (const auto & interface_params)> cls_allocator);
मैं अजगर प्रभाव जहां सिर्फ कार्य करने के लिए वर्ग प्रकार पारित कर सकते हैं इस पर आ रहा हूँ।
स्रोत
2016-02-26 18:00:31
@ मार्टिन, यह "अपेक्षाकृत नया" की एक दिलचस्प परिभाषा है, जो कि स्मॉलटाक पर विचार कर रही थी, जो कि अपने समय में काफी मुख्यधारा थी, और इसमें बहुत कुछ कोड लिखा गया था, बस 70 के दशक में :) –
कई लोगों के साथ स्मॉलटाक को जिम्मेदार चीजें, लिस्प 1 9 50 के दशक में थी - पूरा कार्यक्रम एक डेटास्ट्रक्चर था जिसका निरीक्षण और छेड़छाड़ की जा सकती थी। –