dimanche 30 octobre 2016

C++11 function signature with variadic std::function

I'm trying to implement a function that takes an std::function which returns an it and might get any number of parameter.

I've tried the following but it doesn't compile and I can't understand what the error means.

template <typename ...Args>
void ThrowOnError(std::function<int(Args...)> func, Args... args)
{
    int err = func(args...);
    if (err < 0)
        throw std::exception();
}

int f()
{
    return 42;
}

int f(int x)
{
    return x;
}


int main()
{
    ThrowOnError(f);
    ThrowOnError(f, 1);
}

I tried moving the templated function to header but it didn't work, also if I comment out the f(int x) function and only leave the call with only f , I still get a no matching overloaded function found and 'void ThrowOnError(std::function<int(Args...)>,Args...)': could not deduce template argument for 'std::function<int(Args...)>' from 'int (int)'

What is the problem here? what am I missing in the function? P.S - I would like an answer which takes an std::function if possible, and not add another typename for the functor type.

Aucun commentaire:

Enregistrer un commentaire