我正在爲C++ 11「LINQ to Objects」庫。 我想這樣做水木清華這樣的:通過函子參數計數類型C++重載
// filtering elements by their value
arr.where([](double d){ return d < 0; })
// filtering elements by their value and position
arr.where([](double d, int i){ return i%2==0; })
我倒想寫arr.where_i(...)
- 它是醜陋的。 所以我需要通過拉姆達型函數/方法重載...
這是我的解決方案:
template<typename F>
auto my_magic_func(F f) -> decltype(f(1))
{
return f(1);
}
template<typename F>
auto my_magic_func(F f, void * fake = NULL) -> decltype(f(2,3))
{
return f(2,3);
}
int main()
{
auto x1 = my_magic_func([](int a){ return a+100; });
auto x2 = my_magic_func([](int a, int b){ return a*b; });
// x1 == 1+100
// x2 == 2*3
}
是否SFINAE解決方案嗎? 你能告訴我什麼?
該解決方案的工作原理,但我需要知道類型的參數寫my_magic_func。它不舒服。 – k06a
你可能想看看boost :: range。 –
我在圖書館工作的主要目標是複製C#LINQ風格...如果你有興趣,你可以在這裏得到它:http://code.google.com/p/boolinq/ – k06a