【发布时间】:2012-05-12 10:23:07
【问题描述】:
我正在为 C++11 开发“LINQ to Objects”库。 我想这样做:
// 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( ... ) - 太丑了。
所以我需要 lambda 类型的函数/方法重载...
这是我的解决方案:
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。不舒服。
-
你可能想看看 boost::range。
-
我正在开发库,主要目标是复制 C# LINQ 样式...如果您有兴趣,可以在这里获取:code.google.com/p/boolinq
-
啊,真酷!我会收藏它!
标签: c++ templates visual-c++ lambda c++11