5
將自由函數用作僞構造函數以避免顯式指定模板參數是否是常見模式/慣用法?使用自由函數作爲僞構造函數來利用模板參數推導
例如,大家都知道std::make_pair
,它使用它的參數來推斷pair
類型:
template <class A, class B>
std::pair<A, B> make_pair(A a, B b)
{
return std::pair<A, B>(a, b);
}
// This allows you to call make_pair(1, 2),
// instead of having to type pair<int, int>(1, 2)
// as you can't get type deduction from the constructor.
的STL也使得<functional>
大量使用這種(bind1st
,not1
,ptr_fun
,等... )
我發現自己經常使用它,所以我只是想知道是否有很多其他人使用它,並且如果有這個模式的名稱?
我當然更喜歡「對象生成器」,因爲「生成器函數」已經具有數學意義。 – 2010-03-17 23:10:24
@Poita_同意。我現在看到它是一個衆所周知的名稱和增強文檔的一部分,所以我認爲我會稱它們爲對象生成器:) – 2010-03-17 23:12:58
我喜歡這個成語,並且結合'auto',您可以製作複雜的模板構造,指定一個模板參數。 – GManNickG 2010-03-17 23:24:26