C ++重载函数参数计数类型 [英] C++ overloading by functor param count type
本文介绍了C ++重载函数参数计数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为C ++ 11的LINQ to Objects库工作。
我想这样做smth:
I am working on "LINQ to Objects" library for C++11. I would like to do smth like this:
// 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类型的函数/方法重载...
I down want to write arr.where_i( ... )
- it's ugly.
So i need function/method overloading by lambda-type...
这是我的解决方案:
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解决方案吗?
您可以向我推荐什么?
Is it SFINAE solution? What can you suggest me?
推荐答案
也许有些不一样:
#include <utility>
template <typename F, typename ...Args>
decltype(f(std::declval<Args>()...) my_magic_func(F f, Args &&... args)
{
return f(std::forward<Args>(args)...);
}
<编辑:您也可以使用 typename std :: result_of< F(Args ...)> :: type
东西。
You can also use typename std::result_of<F(Args...)>::type
for the return type, which does the same thing.
这篇关于C ++重载函数参数计数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文