Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overloading by functor param count type

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; } )

I down want to write arr.where_i( ... ) - it's ugly. So i need function/method overloading by lambda-type...

This is my solution:

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
}

Is it SFINAE solution? What can you suggest me?

like image 262
k06a Avatar asked Apr 20 '26 10:04

k06a


1 Answers

Maybe something variadic:

#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)...);
}

Edit: You can also use typename std::result_of<F(Args...)>::type for the return type, which does the same thing.

like image 121
Kerrek SB Avatar answered Apr 22 '26 22:04

Kerrek SB