C ++ overload by paramator param parameter

I am working on the LINQ to Objects library for C ++ 11. I would like to do something 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 want to write arr.where_i( ... )- it's ugly. So I need a function / method overload with lambda type ...

This is my decision:

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 this a SFINAE solution? What can you offer me?

+3
source share
2 answers

Maybe something is variable:

#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...)>::typefor the return type, which does the same thing.

+3
source

You definitely want SFINAE to be in your solution. Generally speaking, the result will look something like this:

template<
    typename Functor
    , typename std::enable_if<
        special_test<Functor>::value
        , int
    >::type = 0
>
return_type
my_magic_func(Functor f);

template<
    typename Functor
    , typename std::enable_if<
        !special_test<Functor>::value
        , int
    >::type = 0
>
return_type
my_magic_func(Functor f);

- , , , special_test . , , ; . . (, lombdas? Monomorphic functors? Polymorphic functors?), , value_type, double .

, , , Callable ( ) bool(value_type); .. :

template<typename Functor, typename ValueType>
struct is_unary_predicate {
    typedef char (&accepted)[1];
    typedef char (&refused)[2];

    void consume(bool);

    template<
        typename X
        , typename Y
        , typename = decltype( consume(std::declval<X>()(std::declval<Y>())) )
    >
    accepted
    test(X&&, Y&&);

    refused test(...);

    static constexpr bool value =
        sizeof test(std::declval<Functor>(), std::declval<ValueType>())
        == sizeof(accepted);
};

is_callable<F, Signature>, - template<typename Functor, typename ValueType> using is_unary_predicate = is_callable<Functor, bool(ValueType)>; ( is_binary_predicate , my_magic_func ). , SFINAE ( ).

+2

All Articles