有時我傾向於寫函數,而不是爲了維護函數調用之間的狀態,而是因爲我想捕獲函數調用之間共享的一些參數。舉個例子:Functors vs. std :: bind
class SuperComplexAlgorithm
{
public:
SuperComplexAlgorithm(unsigned int x, unsigned int y, unsigned int z)
: x_(x), y_(y), z_(z)
{}
unsigned int operator()(unsigned int arg) const /* yes, const! */
{
return x_ * arg * arg + y_ * arg + z_;
}
private:
// Lots of parameters are stored as member variables.
unsigned int x_, y_, z_;
};
// At the call site:
SuperComplexAlgorithm a(3, 4, 5);
for(unsigned int i = 0; i < 100; ++i)
do_stuff_with(a); // or whatever
相比
unsigned int superComplexAlgorithm(unsigned int x, unsigned int y,
unsigned int z, unsigned int arg)
{
return x * arg * arg + y * arg + z;
}
// At the call site:
auto a = std::bind(superComplexAlgorithm, 3, 4, 5, std::placeholders::_1);
for(unsigned int i = 0; i < 100; ++i)
do_stuff_with(a);
第一個解決方案有很多缺點的,在我看來:什麼x
,y
,z
做的是分裂
- 文檔在不同的地方(構造函數,類定義,
operator()
)。 - 大量的鍋爐代碼。
- 較不靈活。如果我想捕獲不同的參數子集,該怎麼辦?
是的,我只是意識到多麼有用boost::bind
或std::bind
即可。現在對於我的問題,我開始在很多代碼中使用它:在任何情況下,我應該考慮使用手寫無狀態函子來綁定泛型函數中的參數嗎?
首先你應該考慮lambdas – stijn
@stijn:我不想在調用站點定義'superComplexAlgorithm',因爲它超級複雜,在很多地方使用,需要測試和文檔等。我可以在這種情況下,我不明白lambdas是如何起作用的,儘管我在其他情況下使用它們很多。 –
@MarkusMayr,你可以用lambda替換'std :: bind'。代替'的std ::綁定(superComplexAlgorithm,3,4,5,性病::佔位符:: _ 1)',你寫'[](INT X){返回superComplexAlgorithm(3,4,5,X); }'。 – avakar